1

I'm generating a keystore+keypair using the following command:

keytool -genkeypair -keyalg RSA -alias zik -keypass blabla -keystore TESTKeystore -storepass 123456 -storetype pkcs12

Then, I try loading the private key in Java:

    char[] password = "123456".toCharArray();
    String alias = "zik";
    FileInputStream fIn = new FileInputStream("TESTKeystore");
    KeyStore keystore = KeyStore.getInstance("pkcs12");
    keystore.load(fIn, password);

    Key k = keystore.getKey("zik", "blabla".toCharArray());

Which throws this error:

Exception in thread "main" 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:454)
    at java.base/sun.security.util.KeyStoreDelegator.engineGetKey(KeyStoreDelegator.java:90)
    at java.base/java.security.KeyStore.getKey(KeyStore.java:1050)
    at Main.main(Main.java:164)
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:975)
    at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
    at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
    at java.base/com.sun.crypto.provider.PKCS12PBECipherCore.implDoFinal(PKCS12PBECipherCore.java:408)
    at java.base/com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndDESede.engineDoFinal(PKCS12PBECipherCore.java:440)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2208)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.lambda$engineGetKey$0(PKCS12KeyStore.java:398)
    at java.base/sun.security.pkcs12.PKCS12KeyStore$RetryWithZero.run(PKCS12KeyStore.java:287)
    at java.base/sun.security.pkcs12.PKCS12KeyStore.engineGetKey(PKCS12KeyStore.java:392)

Such a simple task. What am I missing here?

Rizon
  • 1,516
  • 4
  • 25
  • 45

1 Answers1

-1

you are specifying 2 aliases, so remove one (personA).

keytool -genkeypair -keyalg RSA -alias zik -keypass blabla -keystore 
TESTKeystore -storepass 123456 -storetype pkcs12

Try this

char[] password = "123456".toCharArray();
String alias = "zik";
FileInputStream fIn = new FileInputStream("TESTKeystore");
KeyStore keystore = KeyStore.getInstance("pkcs12");
keystore.load(fIn, password);

Key k = keystore.getKey(alias, "blabla".toCharArray()); //load alias here
Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
  • Thanks, but leaving only one alias didn't solve the problem.. (it was a typo which the keytool probably ignored and used the second alias anyway) – Rizon Jan 06 '20 at 02:16