This question already has an answer here:
BadPaddingException loading p12 keystore
                                
                                    (1个答案)
                                
                        
                3个月前关闭。
            
        

我正在使用以下命令生成密钥库+密钥对:

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


然后,我尝试在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());


引发此错误:

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)


如此简单的任务。我在这里想念什么?

最佳答案

您要指定2个别名,因此删除一个(personA)。

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


尝试这个

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

10-07 13:17