Java KeyStore setEntry() using an AES SecretKey

2019-05-17 18:34发布

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.

1条回答
ら.Afraid
2楼-- · 2019-05-17 18:44

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.

查看更多
登录 后发表回答