我创建了两个助手函数(一个用于ByteBuffer到String,反之亦然(
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));
}
我有一个数据密钥,我正在使用AWS KMS加密,它提供了我的ByteBuffer。
// 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);
但这是有效的。
DecryptRequest req1 = new DecryptRequest().withCiphertextBlob(ciphertext).withKeyId(keyId);
我的代码出了什么问题?
尝试将任意字节数组转换为bb_to_str(ciphertext, charset);
中的String时出错。
ciphertext
没有以任何合理的方式表示可读字符串,也绝对没有使用您指定的字符集(无论是哪一个(。
String
用于表示Unicode文本。试图用它来表示其他任何东西都会遇到很多问题(主要与编码有关(。
在一些编程语言中,字符串类型是二进制字符串(即不严格表示Unicode文本(,但这些语言通常会导致大量编码混乱。
如果出于某种原因,您想将任意的byte[]
表示为String
,那么您需要选择一些编码来表示它。常见的编码是Base64或十六进制字符串。Base64更紧凑,十六进制字符串在概念上更简单,但对于相同数量的输入数据,它占用了更多的空间。