1 year ago
#369063
theencodedbong
Java Security: KeyStore.SecretKeyEntry unable to fetch key stored using keytool -genseckey command
I am facing an issue while trying to fetch the secret key entry from a keystore, created to store the password for a service account.
My keytool command reads as below:
keytool -genseckey -alias securesvc -keyalg AES -keysize 256 -keystore myseckey.jceks -storetype JCEKS -storepass myseckey
Next, I am trying to extract the key for securesvc using KeyStore.SecretKeyEntry:
1 String keystorePath = "security/myseckey.jceks";
2 char[] keystorePass = "myseckey".trim().toCharArray();
3 KeyStore ks = KeyStore.getInstance(new File(keystorePath), keystorePass);
4 try (FileInputStream fis = new FileInputStream(keystorePath)) {
5 ks.load(fis, keystorePass);
6 }
7 KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(keystorePass);
8 KeyStore.SecretKeyEntry ske = (SecretKeyEntry) ks.getEntry("securesvc", pp);
9 SecretKey sk = ske.getSecretKey();
10 String securedKey = new String(Base64.getDecoder().decode(sk.getEncoded()));
But, I keep getting the exception below:
Exception in thread "main" java.security.UnrecoverableKeyException: 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.KeyProtector.unseal(KeyProtector.java:399)
at java.base/com.sun.crypto.provider.JceKeyStore.engineGetKey(JceKeyStore.java:146)
at java.base/java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:499)
at java.base/java.security.KeyStore.getEntry(KeyStore.java:1548)
at com.practice.TestClass.getSecretKey(TestClass.java:8)
Can anyone point out where I am possibly going wrong here, and suggest a solution? Thanks in advance.
java
keystore
keytool
secret-key
java-security
0 Answers
Your Answer