I have stored the SecretKey
during some encryption operation which I need to use later. While storing I am converting it into string :
String keyAsString = new Gson().toJson(key);
But while retriving it fails for following code :
SecretKey secKey = new Gson().fromJson(keyAsString, SecretKey.class);
Also I am not getting any single hint in LogCat even with Verbose messaging filter. I tried surrounding the code in try catch as below with debug points ( In hope I may get any exception trace while debugging ) :
try {
SecretKey secKey = new Gson().fromJson(keyAsString, SecretKey.class); // One debug point here
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); // And one debug point here
}
But debugger do not stop at both the debug points, Immediately on device app crashes and shows unfortunately application crashed message.
The json structure on save for SecretKey
is as follow :
{
"algorithm": "AES",
"key": [
integer1, integre2, ....
]
}
Note : integer1, integer2 ... are actual numbers for security purpose I am not posting the original result numbers.
What may have gone wrong ? Is such storing of SecretKey
is not allowed ?
Update
Converting SecretKey to json string & vice versa using Gson was bad Idea as answered by jonathanrz below I followed his answer & wrote two utility functions in android to convert SecretKey to String & vice versa functions are as follows :
public static String secretKeyToString(SecretKey key) {
return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
}
public static SecretKey encodedStringToSecretKey(String encodedKey) {
byte[] decodedKey = Base64.decode(encodedKey, Base64.DEFAULT);
return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
}