0

I'm trying to use RSA algorithm and PKCS1Padding for encryption the given password but when cipher.doFinal() is called the BadPaddingException is thrown.

Here is the code :

String rsaKeyAlgorithm = "RSA";
String rsaEncryptAlgorithm = "RSA/ECB/PKCS1Padding";

PrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance(rsaKeyAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privKey.getBytes(StandardCharsets.UTF_8))));

byte[] bytes = Base64.getDecoder().decode(dataKey.getBytes(StandardCharsets.UTF_8));

Cipher cipher = Cipher.getInstance(rsaEncryptAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
System.out.println(new String(cipher.doFinal(bytes)));

I've also reading some articles about encryption by specific provider for example SUN may cause BadPaddingException because different Java versions may have not the specific provider and removed the provider from the KeyFactory.getInstance method. But now have issue about how default (non-specific) provider on this method is handling the different Java versions on different environments ?

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27
  • 1
    The exception can have various causes, e.g. wrong key, wrong padding, corrupted ciphertext. Post the encryption code and if possible non-productive sample data. – Topaco Jun 19 '23 at 11:43
  • The code and config files are same in both productive and development. working on development well but on productive not work and gives exception. – Mohammadreza Khatami Jun 19 '23 at 11:51
  • @Topaco I got a guess.. when i generate the hibernate-key file and then encrypt passwords and copying both hibernate-key and keystore file on productive code from development. Everything works fine! But i shouldn't create hibernate-key file everytime.. So what is going on ? Do you have any idea ? – Mohammadreza Khatami Jun 19 '23 at 12:04

1 Answers1

0

After spending about two days finally my issue get solved! the problem was in generating and copying the keys (hibernate-keystore.key) file also those keys create each time so entering previous passwords get badPaddingException because they aren't in keystore file anymore.

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27