问题描述
我创建了两个辅助函数(一个用于将ByteBuffer转换为String,反之亦然)
Confluence(
url='https://my.domain.com',username='admin',password='admin',verify_ssl=False
)
我有一个数据密钥,正在使用提供我的ByteBuffer的AWS KMS进行加密。
public static Charset charset = Charset.forName("UTF-8");
public static String bb_to_str(ByteBuffer buffer,Charset charset){
System.out.println("Printing start");
byte[] bytes;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
return new String(bytes,charset);
}
public static ByteBuffer str_to_bb(String msg,Charset charset){
return ByteBuffer.wrap(msg.getBytes(charset));
}
现在的问题是,这不起作用:
// Encrypt the data key using AWS KMS
ByteBuffer plaintext = ByteBuffer.wrap("ankit".getBytes(charset));
EncryptRequest req = new EncryptRequest().withKeyId(keyId);
req.setPlaintext(plaintext);
ByteBuffer ciphertext = kmsClient.encrypt(req).getCiphertextBlob();
// Convert the byte buffer to String
String cip = bb_to_str(ciphertext,charset);
但这是可行的。
DecryptRequest req1 = new DecryptRequest().withCiphertextBlob(str_to_bb(cip,charset)).withKeyId(keyId);
我的代码有什么问题?
解决方法
该错误正在尝试将任意字节数组转换为bb_to_str(ciphertext,charset);
中的字符串。
ciphertext
不会以任何合理的方式表示可读的字符串,并且绝对不会使用您指定的字符集(无论是哪个字符集)。
String
用于表示Unicode文本。试图用它来表示其他任何东西都会遇到很多问题(大多数与编码有关)。
在某些编程语言中,字符串类型是二进制字符串(即严格不表示Unicode文本),但通常是相同的语言,会引起大量的编码混乱。
如果出于某种原因想要将任意byte[]
表示为String
,则需要选择一些编码来表示它。常见的一种是Base64或十六进制字符串。 Base64更加紧凑,十六进制字符串在概念上更简单,但是在相同数量的输入数据下占用更多空间。