带有垃圾字符的 RSA AES 解密

RSA AES decryption with junk characters

我正在尝试使用 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]����

看来你的IV值是加在密文前面的。您应该将密文的前 16 个字节用于 cipher2,而不是零 IV。不要忘记将它们排除在加密之外。这解释了开头的垃圾。

您的 cipher2 似乎也应该配置为填充。这可能是 PKCS#7 填充。请尝试 "AES/CBC/PKCS5Padding" 而不是 "/NoPadding"。如果这不起作用,您需要使用十六进制 中的纯文本 更新您的问题,以便我们确定使用了哪个填充。那应该解释最后的垃圾。

请注意 Java 中的 "PKCS5Padding" does perform PKCS#7 padding