Converted SecretKey into bytes, how to convert it back to a SecretKey?

Princeyesuraj picture Princeyesuraj · Mar 19, 2011 · Viewed 44.2k times · Source

I convert the secretkey into bytes with following code

SecretKey key = KeyGenerator.getInstance("DES").generateKey();
byte[] bkey=key.getEncoded();

Now how do I get the key from bkey? I tried:

SecretKeySpec secretkey = new SecretKeySpec(bkey,"DES");   
SecretKeyFactory sfkey = SecretKeyFactory.getInstance("DES");
SecretKey skey = sfkey.generateSecret(secretkey);

I get the following error:

Error during Exception java.security.spec.InvalidKeySpecException: Inappropriate key specification

Answer

MeBigFatGuy picture MeBigFatGuy · Mar 19, 2011

This should work

    SecretKey key = KeyGenerator.getInstance("DES").generateKey();
    byte[] data = key.getEncoded();
    SecretKey key2 = new SecretKeySpec(data, 0, data.length, "DES");