在Java AWS SDK中解密数据密钥会产生乱码

时间:2017-10-02 23:28:42

标签: java encryption bytebuffer aws-kms

因此,我一直在阅读和阅读并查看示例......并且悲惨地失败了。这是我的情况:

我在KMS中有一个CMK,并且我已经生成了一个数据密钥,如下所示:

$ aws kms generate-data-key --key-id 64a62e3e-7e38-4f86-8ef2-3d00929e6260 --key-spec AES_256
{
   "Plaintext": "+SjeaxtD5TIhOcY16+A2NA493MbxnYozbzZx4i3/BfA=", 
   "KeyId": "arn:aws:kms:us-west-2:040512153658:key/64a62e3e-7e38-4f86-8ef2-3d00929e6260", 
   "CiphertextBlob": "AQIDAHgrvfqfgn9D0tTUJOISzFCz7ejMPZ6/HGX0kGAlzKYZ7wEiyHdpuGaOjpq4UQazPAgeAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMU5JtbI6lxLOv/p4KAgEQgDsX97Pk+ywqLU2VymLRgDSz0exOyzRgLMgd7WEf3sLUh4GnbYllIrxNSdK/DSZrYUhBo78KYugnkTj89g=="
}

然后我通过CLI解密验证它:

$ aws kms decrypt --ciphertext-blob fileb://<(echo 'AQIDAHgrvfqfgn9D0tTUJOISzFCz7ejMPZ6/HGX0kGAlzKYZ7wEiyHdpuGaOjpq4UQazPAgeAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMU5JtbI6lxLOv/p4KAgEQgDsX97Pk+ywqLU2VymLRgDSz0exOyzRgLMgd7WEf3sLUh4GnbYllIrxNSdK/DSZrYUhBo78KYugnkTj89g==' | base64 -d) --query Plaintext
"+SjeaxtD5TIhOcY16+A2NA493MbxnYozbzZx4i3/BfA="

瞧瞧!我得到的明文价值一切都很好,干净。然后我尝试使用Java使用以下代码在SDK中研磨相同的密文blob:

    .
    .
    .
    final String encryptedCipherText = "AQIDAHgrvfqfgn9D0tTUJOISzFCz7ejMPZ6/HGX0kGAlzKYZ7wEiyHdpuGaOjpq4UQazPAgeAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMU5JtbI6lxLOv/p4KAgEQgDsX97Pk+ywqLU2VymLRgDSz0exOyzRgLMgd7WEf3sLUh4GnbYllIrxNSdK/DSZrYUhBo78KYugnkTj89g==";
    final String expectedPlainText = "+SjeaxtD5TIhOcY16+A2NA493MbxnYozbzZx4i3/BfA=";

    AWSKMS kmsClient;
    String returnValue;

    kmsClient = AWSKMSClientBuilder
            .standard()
            .withRegion("us-west-2")
            .build();

    ByteBuffer cipherTextBlob = ByteBuffer.wrap(Base64.getDecoder().decode(encryptedCipherText));
    DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(cipherTextBlob);
    ByteBuffer key = kmsClient.decrypt(decryptRequest).getPlaintext();
    final byte[] bytes = new byte[key.remaining()];
    key.duplicate().get(bytes);
    String result = new String(bytes);
    if (expectedPlainText.equals(result)) {
        LOG.info("decrypted plaintext matches expected");
    } else {
        LOG.error("decrypted plaintext unexpected value: " + result);
    }
    .
    .
    .

转出的LOG条目是:

23:08:33.210 [main] ERROR com.eyefinity.magicmissile.aws.AwsClientConfig - decrypted plaintext unexpected value: �(�k�2!9�5��64=���3o6q�-��

我尝试使用每个可用的Charset对结果进行编码,并且没有Charset生成我原始的纯文本密钥。从我所见过的所有例子中可以看出,我的代码是正确的。那么我做错了什么或我在这里错过了什么?我想要的只是最终得到一个包含&#34; + SjeaxtD5TIhOcY16 + A2NA493MbxnYozbzZx4i3 / BfA =&#34;的Java字符串变量。

1 个答案:

答案 0 :(得分:0)

我偶然发现了自己的解决方案:我太紧张了!上面代码中提取的所有内容都提取了从KMS返回的相同纯文本值,以及我在生成数据密钥时在aws-cli命令行上收到的ASCII字符串,即采用字节数组和Base64编码它。所以引用我上面的示例代码,一直到顶部,替换读取的行......

String result = new String(bytes);

有这样的事情:

String result = Base64.getEncoder().encodeToString(bytes);