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
The line where you execute:
Is inside a try catch block which may cause it not to execute, so if that happens when you reach this line:
The KeyStore is in fact not initialized, and thus, the exception. Your try-catch block is there for to deal with the FileInputStream exceptions, try moving the KeyStore#load call outside of it.
According to the
KeyStore
documentation ,so you are loading the KeyStore but what if a
FileNotFoundException
occures atfis = new java.io.FileInputStream("keyStoreName");
, hence if file does not exist we load the KeyStore withnull
values ,like ,ks.load(null,null);
.