Converting Secret Key into a String and Vice Versa

Princeyesuraj :

I am generating a key and need to store it in DB, so I convert it into a String, but to get back the key from the String. What are the possible ways of accomplishing this?

My code is,

SecretKey key = KeyGenerator.getInstance("AES").generateKey();
String stringKey=key.toString();
System.out.println(stringKey);

How can I get the key back from the String?

Jabari :

You can convert the SecretKey to a byte array (byte[]), then Base64 encode that to a String. To convert back to a SecretKey, Base64 decode the String and use it in a SecretKeySpec to rebuild your 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 to 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 store the byte[] in SQLite. That said, performing Base64 encoding/decoding is not an expensive operation and you can store strings in almost any DB without issues.

NOTE II: Earlier Java versions do not include a Base64 in one of the java.lang or java.util packages. It is however possible to use codecs from Apache Commons Codec, Bouncy Castle or Guava.

SecretKey to String:

// CREATE NEW KEY
// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)

    SecretKey secretKey;
    String stringKey;

    try {secretKey = KeyGenerator.getInstance("AES").generateKey();}
    catch (NoSuchAlgorithmException e) {/* LOG YOUR EXCEPTION */}

    if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}

String to 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");

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

String to Secret key conversion/Vice Versa

Converting String to Byte Array and vice versa

Converting string to integer and vice versa in Python

Overhead of converting from []byte to string and vice-versa

Converting Date to string and vice versa returns error message

Java - Converting String from Scanner to int and vice versa

Converting XDocument to XmlDocument and vice versa

byte to string and vice versa

Java String to Json & vice versa

Object to string, and vice-versa

R - Converting formulae to character strings and vice versa

"Converting" Numpy arrays to Matlab and vice versa

"Converting" Numpy arrays to Matlab and vice versa

Converting Strings to encryption keys and vice versa java

Converting pandas dataframe to dict and vice versa

Converting a population on a grid to coordinates, and vice versa

Converting QString to Ascii value & Vice Versa in Qt

Converting an Armadillo Matrix to an Eigen MatriXd and vice versa

Converting Double to Float and vice versa manually

Converting base 6 to decimal and vice versa in Python?

Converting char to binary strings and vice-versa

Which optimisations does the Go 1.6 compiler apply when converting between []byte and string or vice versa?

Why does a number as key worked for a string key in an Object and vice-versa (Javascript)

How to convert String[] to String and vice versa in Android

Convert List<int> to string and vice versa?

How to convert a netty ByteBuf to a String and vice versa

How to convert numpy array to string and vice versa

how to convert joda datetime to String and vice versa

How to convert byte array to string and vice versa?