AES转码问题
aes加密解密过程中,由于是在jetty服务下开发的,运行中文不乱码,但是在测试在tomcat下还是出现了中文乱码(已经在server.xml配过了utf-8编码格式),然后就是一系列转码过程,在这过程中知道,gbk转utf-8乱造成字节流失,造成奇数中文奇数乱码,最后解决方法是解密字节码时就转码,相对应的加密的时候也要转码:
/**
* aes解密
* @param encryptbytes 待解密的byte[]
* @param decryptkey 解密密钥
* @return 解密后的string
* @throws exception
*/
public static string aesdecryptbybytes(byte[] encryptbytes, string decryptkey) throws exception {
keygenerator kgen = keygenerator.getinstance("aes");
kgen.init(128);
cipher cipher = cipher.getinstance(algorithmstr);
cipher.init(cipher.decrypt_mode, new secretkeyspec(decryptkey.getbytes(), "aes"));
byte[] decryptbytes = cipher.dofinal(encryptbytes);
return new string(decryptbytes,"utf-8"); //此处需转码
}
/**
* aes加密
* @param content 待加密的内容
* @param encryptkey 加密密钥
* @return 加密后的byte[]
* @throws exception
*/
public static byte[] aesencrypttobytes(string content, string encryptkey) throws exception {
keygenerator kgen = keygenerator.getinstance("aes");
kgen.init(128);
cipher cipher = cipher.getinstance(algorithmstr);
cipher.init(cipher.encrypt_mode, new secretkeyspec(encryptkey.getbytes(), "aes"));
return cipher.dofinal(content.getbytes("utf-8"));
}