Storing AES Secret key using keystore in java

时光怂恿深爱的人放手 提交于 2019-12-09 12:57:29

问题


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

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)

How to fix this error? Thanks in advance


回答1:


According to the KeyStore documentation ,

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

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



来源:https://stackoverflow.com/questions/21406884/storing-aes-secret-key-using-keystore-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!