Reputation: 51
This my code used for usage of key store.While I am running my app it is showing an exception that key store is not initialized.
try {
KeyStore ks = KeyStore.getInstance("JKS");
pk = ks.getKey("Alias", null);
if(pk != null){
sendSMS("5556", Base64.encodeToString(pk.getEncoded(), Base64.DEFAULT));
}
}
catch (KeyStoreException e) {
e.printStackTrace();
}
catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
catch (UnrecoverableKeyException e){
e.printStackTrace();
}
try {
ks.deleteEntry("Alias");
ks.setKeyEntry("Alias", privateKey.getEncoded(), null);
}
catch (KeyStoreException e) {
e.printStackTrace();
}
catch(NullPointerException e){
e.printStackTrace();
}
Upvotes: 3
Views: 16902
Reputation: 870
Try:
ks.load(null)
?
That will initialize the keystore with the default values.
That should be enough for your example.
Upvotes: 2
Reputation: 5701
You use the variable 'ks' out of scope. The lines
ks.deleteEntry("Alias");
ks.setKeyEntry("Alias", privateKey.getEncoded(), null);
need to be in the same try{
block as KeyStore ks = KeyStore.getInstance("JKS");
You also need to initialize the keystore, by using the load(..)
method: http://developer.android.com/reference/java/security/KeyStore.html#load(java.io.InputStream, char[])
Using your example code, that would be:
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
pk = ks.getKey("Alias", null);
if(pk != null){
sendSMS("5556", Base64.encodeToString(pk.getEncoded(), Base64.DEFAULT));
}
ks.deleteEntry("Alias");
ks.setKeyEntry("Alias", privateKey.getEncoded(), null);
}
catch (KeyStoreException e) {
e.printStackTrace();
}
catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
catch (UnrecoverableKeyException e){
e.printStackTrace();
}
Upvotes: 2
Reputation: 8617
Because ks
is a local variable declared in a try block. This makes it local to that try itself and inaccessible to any other outer block.
Change,
try {
KeyStore ks = KeyStore.getInstance("JKS");
To,
KeyStore ks;
try {
ks = KeyStore.getInstance("JKS");
This would avoid pushing ks
out of scope when your first try block ends.
Upvotes: 1