1

Why does the following test fail?

KeyGenerator generator = KeyGenerator.getInstance("AES");
SecretKey key = generator.generateKey();
byte[] symKey = key.getEncoded();
String keyAsString = new String(symKey, Charset.forName("UTF-8"));
byte[] supposedSymKey = keyAsString.getBytes(Charset.forName("UTF-8"));
Assert.assertEquals(symKey.length, supposedSymKey.length);

And the contents of supposedSymKey and symKey is different? What is the right way to transform the symKey to string, so that i can distribute it? Thanks.

rok
  • 9,403
  • 17
  • 70
  • 126
  • 1
    The key is not UTF encoded by default, the bytes of the supposedSymKey are not the same, I would say the simplest way to represent it as string is as hex-string. take a look here: http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java – MByD Feb 26 '14 at 18:21

1 Answers1

2

Try base64 encode/decode:

KeyGenerator    generator       = KeyGenerator.getInstance( "AES" );
SecretKey       key             = generator.generateKey();
byte[]          symKey          = key.getEncoded();
String          buffer          = DatatypeConverter.printBase64Binary( symKey );
byte[]          supposedSymKey  = DatatypeConverter.parseBase64Binary( buffer );
Maxim
  • 339
  • 1
  • 5
  • Or hex, as an alternative. Strange formatting in this answer - is this how you format all your code? – Duncan Jones Feb 26 '14 at 20:11
  • For me it is very convenient to format source code in this way: 1) I use C, C++, C# and Java in the same time as result I need the same way to format sources for all these languages... – Maxim Feb 27 '14 at 07:51