【问题标题】:ByteBuffer to String & VIce Versa diferent resultByteBuffer 到 String 和 VIce Versa 不同的结果
【发布时间】:2020-10-13 09:53:16
【问题描述】:

我创建了两个辅助函数(一个用于 ByteBuffer 到字符串,反之亦然)

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

我的代码有什么问题?

【问题讨论】:

    标签: bytebuffer aws-kms


    【解决方案1】:

    错误是试图将任意字节数组转换为bb_to_str(ciphertext, charset); 中的字符串。

    ciphertext 不以任何合理的方式表示可读字符串,并且绝对不使用您指定的字符集(无论它是哪一个)。

    String 用于表示 Unicode 文本。试图用它来表示其他任何东西都会遇到很多问题(主要与编码有关)。

    一些编程语言中,字符串类型是二进制字符串(即不严格表示 Unicode 文本),但这些通常是导致大量编码混淆的相同语言。

    如果您出于某种原因想将任意byte[] 表示为String,那么您需要选择一些编码来表示它。常见的一种是 Base64 或十六进制字符串。 Base64 更紧凑,十六进制字符串在概念上更简单,但对于相同数量的输入数据会占用更多空间。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多