views:

24

answers:

1

If I generate a key like this:

SecretKey aesKey    = KeyGenerator.getInstance("AES").generateKey();

Then decode it:

System.out.println("used key: " + aesKlic.getEncoded());

And now I want to use it for decryption(after exiting program and starting again). Obviously, something like this does not work:

SecretKey aesKey    = javax.crypto.spec.SecretKeySpec@[B@6c6e70c7;

if the string at the end is decoded key.

+1  A: 

getEncoded() returns a byte[], whose implementation of toString() is not what you are looking for.

You are perhaps either looking for a hex, or a base64 representation of your key.

For hex, you can use Hex.encodeHex(byte[])

For base64 - Base64.encodeBase64String(byte[])

(both from apache commons-codec)

When you need to restored the string-encoded key (e.g. when you start your program again), you will have to call the decoding equivalents of the above methods (they in the same classes).

Bozho