0

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

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);
Community
  • 1
  • 1
  • Please show us where this hint of divanov is given. **Never** use Sun internal classes; use Bouncy Castle lightlweight API as you have to. Oracle may change location and/or implementation at any time. – Maarten Bodewes Jul 21 '14 at 20:18
  • http://stackoverflow.com/questions/23844694/bad-padding-exception-rsa-ecb-oaepwithsha-256andmgf1padding-in-pkcs11/23853610#23853610 – user3860806 Jul 22 '14 at 08:45

1 Answers1

0

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

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

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263