使用JAVA将AES对称密钥作为字符串传递

时间:2014-02-26 18:13:28

标签: java string encryption encryption-symmetric

为什么以下测试失败?

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

guessSymKey symKey 的内容有何不同? 将 symKey 转换为字符串的正确方法是什么,以便我可以分发它? 感谢。

1 个答案:

答案 0 :(得分:2)

尝试base64编码/解码:

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