【发布时间】:2015-03-23 23:34:02
【问题描述】:
我正在尝试使用 AES 和 RSA 解密 saml 响应,并且可以正确解密 saml 断言。但是,解密后的文本被嵌入到一些垃圾字符中,导致解析异常。
下面是我的代码
InputStream privateKeyFileInputStream = Check.class.getClassLoader().getResourceAsStream("rsa_privatekey.key");
rsaPrivateKey = new byte[privateKeyFileInputStream.available()];
privateKeyFileInputStream.read(rsaPrivateKey);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PrivateKey privKey = keyFactory.generatePrivate(privateKeySpec);
Cipher cipher1 = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
cipher1.init(Cipher.DECRYPT_MODE, privKey);
byte[] encryptedMessage = Base64.decodeBase64(aesPrivateKeyEnc.getBytes());
aesPrivateKey = cipher1.doFinal(encryptedMessage);
IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
SecretKeySpec key = new SecretKeySpec(aesPrivateKey, "AES");
Cipher cipher2 = Cipher.getInstance("AES/CBC/NoPadding", "BC");
cipher2.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] cipherTextBytes = Base64.decodeBase64(cipherText);
byte[] decryptedMessage = cipher2.doFinal(cipherTextBytes);
String message = new String(decryptedMessage, "UTF8");
现在,消息有
R����=2�W���?<saml:Assertion ...... </saml:Assertion>��fE]����
【问题讨论】:
-
您没有保留 unicode 字符,或者您在打印消息的任何地方都不支持显示它们。控制台默认没有。
-
如何保存?解密的文本(在垃圾字符之间)没有任何问题。
-
“我如何保存?” - 到处使用 UTF-8 进行系统互连。它最具互操作性。您可能仍需要转换为本地编码(如 Windows 上的 UTF-16)。
标签: java encryption aes rsa saml