Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java KeyStore setEntry() using an AES SecretKey

I'm currently working on an key-handling class in Java, specifically using a KeyStore. I'm trying to generate a SecretKey with an AES instance, then place it inside of the KeyStore using the setEntry() method.

I've included the relevant sections of my code:

// The KS Object
private KeyStore keyStore;

private KeyStore.SecretKeyEntry secretKeyEntry;
private KeyStore.ProtectionParameter protectionParameter;

private KeyGenerator keyGenerator;
private SecretKey secretKey, newSecretKey;


keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);

newSecretKey = keyGenerator.generateKey();

protectionParameter = new KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray());
secretKeyEntry = new KeyStore.SecretKeyEntry(newSecretKey);

keyStore.setEntry(KEYSTORE_ALIAS, secretKeyEntry, protectionParameter);

The two constants I've used are defined as Strings, too.

The Exception I keep getting is in my setEntry() call:

java.security.KeyStoreException: Cannot store non-PrivateKeys
at sun.security.provider.JavaKeyStore.engineSetKeyEntry(Unknown Source)
at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(Unknown Source)
at java.security.KeyStoreSpi.engineSetEntry(Unknown Source)
at java.security.KeyStore.setEntry(Unknown Source)

I'm using mainly this document http://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.html as a reference, along with some other sources.

Thanks in advance for any help.

like image 716
James Avatar asked Aug 14 '26 16:08

James


1 Answers

I found this as a non-accepted answer on stackoverflow:

The "Cannot store non-PrivateKeys" error message usually indicates you are trying to use secret symmetric keys with a JKS keystore type. The JKS keystore type only supports asymmetric (public/private) keys. You would have to create a new keystore of type JCEKS to support secret keys.

It is very hard to confirm this, although my memory tells me it is correct.

like image 119
Maarten Bodewes Avatar answered Aug 16 '26 07:08

Maarten Bodewes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!