[英]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值似乎以密文為前綴。 代替零IV,您應該將密文的前16個字節用於cipher2
。 不要忘記將它們從加密中排除。 這從一開始就說明了垃圾。
似乎您的cipher2
應該配置為填充。 這可能是PKCS#7填充。 請嘗試使用"AES/CBC/PKCS5Padding"
代替"/NoPadding"
。 如果這樣不起作用,則需要用十六進制的明文更新您的問題,以便我們確定使用哪種填充。 那應該在最后解釋垃圾。
請注意, "PKCS5Padding"
確實在Java 中執行PKCS#7填充 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.