为什么以下测试失败?

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);


假设的symKey和symKey的内容不同吗?
将symKey转换为字符串的正确方法是什么,以便我可以分发它?
谢谢。

最佳答案

尝试base64编码/解码:

KeyGenerator    generator       = KeyGenerator.getInstance( "AES" );
SecretKey       key             = generator.generateKey();
byte[]          symKey          = key.getEncoded();
String          buffer          = DatatypeConverter.printBase64Binary( symKey );
byte[]          supposedSymKey  = DatatypeConverter.parseBase64Binary( buffer );

07-27 13:33