为什么以下测试失败?
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 转换为字符串的正确方法是什么,以便我可以分发它? 感谢。
答案 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 );