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

时间:2014-07-21 14:41:31

标签: java encryption bouncycastle smartcard pkcs#11

使用"RSA/ECB/NoPadding"算法解密并使用the approach given by 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)

使用相同的代码,但它对我不起作用。

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

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 个答案:

答案 0 :(得分:0)

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

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