Home > Software design >  "Get Key Failed: Given final block not properly padded" when I try loading .p12 certificat
"Get Key Failed: Given final block not properly padded" when I try loading .p12 certificat

Time:09-25

Specifically, the relevant part of the code looks like this (capitalized words are placeholders):

FileInputStream("PATH TO P12 FILE");

 KeyStore keyStore = KeyStore.getInstance( "PKCS12" );

 keyStore.load( file_inputstream, "PASSWORD".toCharArray() );

 Key privatni = keyStore.getKey( "ALIAS", " PASSWORD ".toCharArray() );

 Signature biljeznik = Signature.getInstance( "SHA256withRSA" );

 biljeznik.initSign( ( PrivateKey )privatni );

 biljeznik.update( medjurezultat.getBytes() );

 potpisano = biljeznik.sign();

I am 100% sure that the password and the alias are correct. I am aware that P12 files can't have 2 passwords like JKS keystores, but I'm not sure how to change the code if that's the problem (the only password is written under both "PASSWORD" placeholders).

The exact error message is this one:

java.security.UnrecoverableKeyException: Get Key failed: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
    at java.base/sun.security.pkcs12.PKCS12KeyStore.engineGetKey(PKCS12KeyStore.java:450)
    at java.base/sun.security.util.KeyStoreDelegator.engineGetKey(KeyStoreDelegator.java:91)
    at java.base/java.security.KeyStore.getKey(KeyStore.java:1050)
    at primjer.ZastitniKodIzracun.main(ZastitniKodIzracun.java:56)
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
    at java.base/com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:859)
    at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:939)
    at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:735)
    at java.base/com.sun.crypto.provider.PKCS12PBECipherCore.implDoFinal(PKCS12PBECipherCore.java:424)
    at java.base/com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndDESede.engineDoFinal(PKCS12PBECipherCore.java:456)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2205)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.lambda$engineGetKey$0(PKCS12KeyStore.java:371)
    at java.base/sun.security.pkcs12.PKCS12KeyStore$RetryWithZero.run(PKCS12KeyStore.java:257)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.engineGetKey(PKCS12KeyStore.java:361)
    ... 3 more

Any assistance is greatly appreciated.

CodePudding user response:

This is a very dumb mistake:

keyStore.load( file_inputstream, "PASSWORD".toCharArray() );
Key privatni = keyStore.getKey( "ALIAS", " PASSWORD ".toCharArray() );

The spaces in the second PASSWORD were causing the error. It should be:

keyStore.load( file_inputstream, "PASSWORD".toCharArray() );
Key privatni = keyStore.getKey( "ALIAS", "PASSWORD".toCharArray() );
  • Related