1

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");
}
Prashant
  • 4,474
  • 8
  • 34
  • 82

1 Answers1

1

You should parse the key as a string and then use the SecretKeyFactory.translateKey to parse the key.

UPDATE: after you edited your question, I saw that the output you have are not just a single String. So you will need to create a class that represents your json, parse the response with it and construct each key with translateKey. GSON can only parse a json if the class has the attributes with the same name and same type as the keys in json, what is not the case for SecretKey.

UPDATE2: translateKey can't create keys from String. The option to create a key from a String is this: Converting Secret Key into a String and Vice Versa

jonathanrz
  • 4,206
  • 6
  • 35
  • 58