I am generating a Secret Key like below :
key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();
And I want to send this key to another activity. If I use intent I think then this need to be converted into a String from Secret key. Can anyone tell me about Secret key conversion/Vice Versa…
Advertisement
Answer
Just follow below steps.
From key to string
JavaScript
x
`SecretKey secretKey = KeyGenerator.getInstance("ALGO_SECRET_KEY_GENERATOR").generateKey();
// Crate base64 string
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());`
From string to key
JavaScript
`// decode base64 string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "ALGO_SECRET_KEY_GENERATOR"); `
It is available from api version 8
JavaScript
`SecretKey secretKey = null;
try {
secretKey = KeyGenerator.getInstance("AES").generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte encoded[] = secretKey.getEncoded();
String str = android.util.Base64.encodeToString(encoded , 0);
byte decoded[] = android.util.Base64.decode(str , 0);
SecretKey originalKey = new SecretKeySpec(decoded, 0, decoded.length, "AES");'