我有一个将javax.crypto.SecretKey存储在密钥库中的方法。每当我调用此方法时。它吐出Exception in thread "main" java.security.KeyStoreException: Cannot store non-PrivateKeys
这是完整的追溯:
Exception in thread "main" java.security.KeyStoreException: Cannot store non-PrivateKeys
at sun.security.provider.JavaKeyStore.engineSetKeyEntry(JavaKeyStore.java:261)
at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(JavaKeyStore.java:56)
at java.security.KeyStoreSpi.engineSetEntry(KeyStoreSpi.java:550)
at sun.security.provider.KeyStoreDelegator.engineSetEntry(KeyStoreDelegator.java:179)
at sun.security.provider.JavaKeyStore$DualFormatJKS.engineSetEntry(JavaKeyStore.java:70)
at java.security.KeyStore.setEntry(KeyStore.java:1557)
at cryptography.Cryptography.storeKey(Cryptography.java:117)
at cryptography.Cryptography.main(Cryptography.java:27)
和相关代码:
public static void storeKey(SecretKey key, char[] password){
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
String keyStoreName = "C:\\Path\\To\\Keystore";
File f = new File(keyStoreName);
if (f.isFile()){
ks.load(new FileInputStream(keyStoreName), password);
}
else{
ks.load(null, null);
ks.store(new FileOutputStream(keyStoreName), password);
}
KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key);
ks.setEntry(entryAlias, skEntry, new KeyStore.PasswordProtection(password));
我遗漏了该方法引发的一些异常以保持其相关性。
我尝试了几种不同的保存密钥的方法,但这似乎是唯一可行的方法。
任何输入或帮助将不胜感激。