3DES encryption and decryption Chinese garbled

The situation is: Chinese strings encrypted by 3DS,

Decryption: There will be no garbled characters in the Windows default character set environment, but Chinese garbled characters may appear in the Linux environment

3DES decryption method:

public  static String decryptThreeDESECB( final String src, final String key) throws Exception {
         // -- decode the string into byte array by base64 
        final BASE64Decoder decoder = new BASE64Decoder();
         final  byte [] bytesrc = decoder.decodeBuffer( src);
         // -- decrypted key 
        DESedeKeySpec dks = null ;
         if (StringUtils.isEmpty(key)){
            dks = new DESedeKeySpec(AppSecret.getBytes("UTF-8")); 
        }else{
            dks= new DESedeKeySpec(key.getBytes("UTF-8"));  
        }
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede" );
         final SecretKey securekey = keyFactory.generateSecret(dks);
         // --Chipher object decryption` 
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding" );
       / / decrypt vector vector
        
        final IvParameterSpec iv = new IvParameterSpec(AppKey.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, securekey,iv);
        final byte[] retByte = cipher.doFinal(bytesrc);
        //return new String(retByte);
     return new String(retByte,"UTF-8");
    }

If the character set of new String(retByte) is not specified at the final return result of the above code, it may cause garbled characters in the linux environment

The reason is that the character set used in your encryption process should be consistent with the character set you used for decryption. If you do not specify the character set for the result: the system character set will be used by default. If it is inconsistent with your encryption process, Chinese garbled characters will easily appear.

Maybe it's not quite right, but it solved the problem in my project perfectly!

This is my first blog essay. It is intended to accumulate bits and pieces of my work, and I hope to help friends solve the same problems.

If there is anything wrong, please leave a message!

Hope to help you!
  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324919723&siteId=291194637