javax.crypto.BadPaddingException:java.security.DigestException:SHA-256digests的长度必须至少为32

时间:2023-01-20 18:30:38

I am getting below exception after decrypting using "RSA/ECB/NoPadding" algorithm and removing OAEP padding using the approach given by divanov.

在使用“RSA / ECB / NoPadding”算法进行解密并使用divanov给出的方法删除OAEP填充之后,我将获得以下异常。

Caused by: javax.crypto.BadPaddingException: java.security.DigestException: Length must be at least 32 for SHA-256digests
    at sun.security.rsa.RSAPadding.mgf1(Unknown Source)
    at sun.security.rsa.RSAPadding.unpadOAEP(Unknown Source)
    at sun.security.rsa.RSAPadding.unpad(Unknown Source)

Used the same code but it didn't work for me.

使用相同的代码,但它不适合我。

The only change I made in the code is following :

我在代码中做的唯一更改如下:

Provider pkcs11provider = new SunPKCS11("C:\\Users\\manishs525\\pkcs11.cfg");
Cipher rsaCipher2 = Cipher.getInstance("RSA/ECB/NoPadding", pkcs11provider);
rsaCipher2.init(Cipher.DECRYPT_MODE, privateKey);
byte[] paddedPlainText = rsaCipher2.doFinal(cipherText);

/* Ensure leading zeros not stripped */
if (paddedPlainText.length < keyLength / 8) {
    byte[] tmp = new byte[keyLength / 8];
    System.arraycopy(paddedPlainText, 0, tmp, tmp.length - paddedPlainText.length, paddedPlainText.length);
    System.out.println("Zero padding to " + (keyLength / 8));
    paddedPlainText = tmp;
}           

System.out.println("OAEP padded plain text: " + DatatypeConverter.printHexBinary(paddedPlainText));
// === changed the next line ===
PSource pSrc = (new PSource.PSpecified(iv));
// === changed the last two parameters to MGF1ParameterSpec.SHA256 and pSrc ===
OAEPParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, pSrc);   // where iv is byte array of length 32
RSAPadding padding = RSAPadding.getInstance(RSAPadding.PAD_OAEP_MGF1, keyLength / 8, new SecureRandom(), paramSpec);
byte[] plainText2 = padding.unpad(paddedPlainText);

1 个解决方案

#1


0  

There seems to be no reason to specify any PSource. In the standards, it seems always empty, allowing for "future extension".

似乎没有理由指定任何PSource。在标准中,它似乎总是空的,允许“未来扩展”。

Are you sure that not just the outside hash is SHA-256? There is no particular security reason to replace the default MGF...

你确定不只是外部哈希是SHA-256吗?更换默认MGF没有特别的安全理由......

#1


0  

There seems to be no reason to specify any PSource. In the standards, it seems always empty, allowing for "future extension".

似乎没有理由指定任何PSource。在标准中,它似乎总是空的,允许“未来扩展”。

Are you sure that not just the outside hash is SHA-256? There is no particular security reason to replace the default MGF...

你确定不只是外部哈希是SHA-256吗?更换默认MGF没有特别的安全理由......