You can convert SecretKey to an array of bytes ( byte[] ), and Base64 to String . To convert back to SecretKey , Base64 decodes the string and uses it in SecretKeySpec to restore the original SecretKey .
For Java 8
SecretKey to String:
// create new key SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); // get base64 encoded version of the key String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
String in SecretKey:
// decode the base64 encoded string byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // rebuild key using SecretKeySpec SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
For Java 7 and before (including Android):
NOTE I: you can skip the Base64 encoding / decoding part and just save the byte[] in SQLite. However, performing Base64 encoding / decoding is not an expensive operation, and you can store strings in almost any database without any problems.
NOTE II: Early versions of Java do not include Base64 in one of the java.lang or java.util packages. However, you can use codecs from Apache Commons Codec , Bouncy Castle, or Guava .
SecretKey to String:
String in SecretKey:
// DECODE YOUR BASE64 STRING // REBUILD KEY USING SecretKeySpec byte[] encodedKey = Base64.decode(stringKey, Base64.DEFAULT); SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
Jabari Aug 20 2018-12-12T00: 00Z
source share