Tomcat:3DES解密时中文乱码

时间:2023-03-09 08:09:30
Tomcat:3DES解密时中文乱码

情况说明:直接用main方法运行时是没有问题的,web程序一放入tomcat中就会出现解密时乱码。

解决办法:

在解密时,返回string时对数组需要指定UTF-8编码。

public static String decode(String desStr) {
Base64 base64 = new Base64();
byte[] keybyte = hex(KEY);
byte[] src = null;
try {
src = base64.decode(desStr.getBytes("UTF-8"));
// 生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
// 解密
Cipher c1 = Cipher.getInstance("DESede");
c1.init(Cipher.DECRYPT_MODE, deskey);
String pwd = new String(c1.doFinal(src),Charset.forName("utf-8"));
return pwd;
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}