以下方法,在java main 函数里面运行,解密的字符串是正常的; 在tomcat里面运行调用时,解密出的字符串含有乱码,请问各位,这是什么原因啊,纠结了好几天。
public static String asynDecrypt() {
//需要解密字符串
String str = "Gl/qCjdyVb6OFc3OVRyKvNnvXMtpy6p98wIr。。。。";//太长了,省略部分字符串
//私钥
String pivateMod = rs.getString("dsf.epay.async.private.mod");
//密码
String pivateD = rs.getString("dsf.epay.async.private.d");
int mode = Cipher.DECRYPT_MODE;
byte[] byteSrc = str.getBytes();
byte[] modBytes = Base64.decode(pivateMod.getBytes());
byte[] dBytes = Base64.decode(pivateD.getBytes());
BigInteger modules = new BigInteger(1, modBytes);
BigInteger d = new BigInteger(1, dBytes);
KeyFactory factory = null;
try {
factory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
e1.printStackTrace();
}
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, d);
PrivateKey privKey = null;
try {
privKey = factory.generatePrivate(privSpec);
} catch (InvalidKeySpecException e2) {
e2.printStackTrace();
}
try {
cipher.init(Cipher.DECRYPT_MODE, privKey);
} catch (InvalidKeyException e1) {
e1.printStackTrace();
}
byteSrc = Base64.decode(byteSrc);
int inputLen = byteSrc.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
try {
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(byteSrc, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(byteSrc, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
byte[] decryptedData = out.toByteArray();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
String retSt = null;
try {
retSt = new String(decryptedData, "UTF-16LE");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retSt;
}
/*********************************************************/
一、 main函数运行效果(正常解密):
<?xml version="1.0" encoding="utf-8"?>
<ParmXMl xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="szedi">
<Status>Error</Status>
<Message>找不到用户</Message>
//其他信息,此处省略
</ParmXMl>
二、在tomcat中运行(出现乱码)
愂彯???<?xml version="1.0" encoding="utf-8"?>
<ParmXMl xmlns:xsd??宏??
如图: