在java中使用密钥库存储AES密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21406884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:32:20  来源:igfitidea点击:

Storing AES Secret key using keystore in java

javaencryptionaeskeystore

提问by user3244519

I am using Java keystore to store the secret key for AES encryption.

我正在使用 Java 密钥库来存储 AES 加密的密钥。

final String strToEncrypt = "Hello World";
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey sk = kg.generateKey();
String secretKey = String.valueOf(Hex.encodeHex(sk.getEncoded()));   
//Storing AES Secret key in keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
char[] password = "keystorepassword".toCharArray();
java.io.FileInputStream fis = null;
try {
  fis = new java.io.FileInputStream("keyStoreName");
  ks.load(fis, password);
} finally {
  if (fis != null) {
    fis.close();
  }

  KeyStore.ProtectionParameter protParam = 
    new KeyStore.PasswordProtection(password);

  KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);
  ks.setEntry("secretKeyAlias", skEntry, protParam);

But i am getting following Exception.

但我正在关注异常。

Exception in thread "main" java.security.KeyStoreException: Uninitialized keystore
at java.security.KeyStore.setEntry(Unknown Source)

线程“main”中的异常 java.security.KeyStoreException:java.security.KeyStore.setEntry 处的未初始化密钥库
(未知来源)

How to fix this error? Thanks in advance

如何修复此错误?提前致谢

回答by Alok Mishra

According to the KeyStoredocumentation ,

根据KeyStore文档,

Before a keystore can be accessed, it must be loaded.

在可以访问密钥库之前,它必须是loaded.

so you are loading the KeyStore but what if a FileNotFoundExceptionoccures at fis = new java.io.FileInputStream("keyStoreName");, hence if file does not exist we load the KeyStore with nullvalues ,like , ks.load(null,null);.

所以你正在加载 KeyStore 但如果发生FileNotFoundExceptionfis = new java.io.FileInputStream("keyStoreName");,因此如果文件不存在,我们会加载 KeyStore 的null值,如 , ks.load(null,null);