5

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

3
  • 3
    Welcome to Stack Overflow! I suggest you read the documentation for the KeyStore class, try something yourself and let us know if you get stuck. Commented Jan 28, 2014 at 13:38
  • Do try and use the jceks key store for at least moderate protection and choose a hard to crack password (like a sentence including made up words). Commented Jan 29, 2014 at 0:22
  • Don't write code like this. Code that depends on the success of code in a prior try block should be inside that try block. In your case, if the file isn't found, the keystores isn't initialised, so you should not execute the remaining code. Commented Apr 16, 2019 at 3:09

1 Answer 1

2

According to the KeyStore documentation ,

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

In order to create an empty keystore, or if the keystore cannot be initialized from a stream, pass null as the stream argument.

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); .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.