问题
I'm currently developing an android application but i'm expecting some issues due to storage and retrieving of a SecretKey into the Keystore
This is my code: Here I generate the SecretKey and then save it into KeyStore, and use it to encrypt my data
try {
KeyStore keyStore=null;
keyStore= KeyStore.getInstance(KeyStore.getDefaultType());
char[] passwordKS="network".toCharArray();
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed("any data used as random seed".getBytes());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, sr);
key= kg.generateKey();
keyToSave=key.getEncoded();
sks = new SecretKeySpec(keyToSave, "AES");
try
{
keyStore.load(null,null);
keyStore.setKeyEntry("aliasKey",key,passwordKS, null);
}
catch(Exception ex)
{
}
FileOutputStream ksout=openFileOutput("keyStoreName", Context.MODE_PRIVATE);
keyStore.store(ksout, passwordKS);
ksout.close();
}
} catch (Exception e) {
}
byte[] userLongENC = null;
byte[] userLatENC=null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,sks );
userLatENC = c.doFinal(userLat.getBytes());
userLongENC = c.doFinal(userLong.getBytes());
} catch (Exception e) {
}
In another activity I try to get back my key from the Keystore and use it to decrypt my data Unfortunately I get this exception back: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
SecretKeySpec sks = null; // Or, equivalently SecretKey sk = null;
SecretKey sk =null;
try {
KeyStore keyStore= KeyStore.getInstance(KeyStore.getDefaultType());
char[] passwordKS="network".toCharArray();
FileInputStream fis =null;
try
{
fis = openFileInput("keyStoreName");
}catch (Exception ex)
{
}
keyStore.load(fis,passwordKS);
//sk=(SecretKey) keyStore.getKey("aliasKey", passwordKS);
sk=(SecretKey) keyStore.getKey("aliasKey", passwordKS);
sks=new SecretKeySpec((keyStore.getKey("aliasKey", passwordKS)).getEncoded(), "AES");
} catch (Exception e) {
}
byte[] latDEC=null;
byte[] longDEC=null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, sks);
latDEC = c.doFinal(lat.getBytes());
longDEC = c.doFinal(longit.getBytes());
} catch (Exception e) {
}
来源:https://stackoverflow.com/questions/24231213/how-to-store-secretkey-in-keystore-and-retrieve-it