You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GCP KMS加密成功但解密失败,请求技术支持

GCP KMS解密失败问题修复

问题根源

加密生成的密文是二进制数据,你直接用toStringUtf8()将其转为字符串,这会破坏原始字节——因为二进制密文并非合法的UTF-8编码内容,转换过程中会丢失或篡改部分字节。解密时基于损坏的字符串生成字节数组,KMS自然无法识别,抛出INVALID_ARGUMENT错误。

修复代码

改用Base64编码处理密文,确保二进制数据完整保留:

import com.google.common.io.BaseEncoding;
import com.google.protobuf.ByteString;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.DecryptResponse;
import com.google.cloud.kms.v1.EncryptResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public String encryptAndDecrypt() throws IOException {

    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

        String plaintext = "Just an ordinary string";
        CryptoKeyName keyVersionName = CryptoKeyName.of("us-con-gcp-npr-0000305-041421",
                "global", "test", "test1");

        // 加密明文
        EncryptResponse response = client.encrypt(keyVersionName, ByteString.copyFromUtf8(plaintext));
        ByteString ciphertextBytes = response.getCiphertext();
        // 用Base64将二进制密文转为字符串
        String cipherText = BaseEncoding.base64().encode(ciphertextBytes.toByteArray());
        System.out.printf("Ciphertext: %s%n", cipherText);

        // 解密:先Base64解码回二进制数据
        byte[] decodedCiphertext = BaseEncoding.base64().decode(cipherText);
        DecryptResponse decryptResponse = client.decrypt(keyVersionName, ByteString.copyFrom(decodedCiphertext));
        System.out.printf("Plaintext: %s%n", decryptResponse.getPlaintext().toStringUtf8());
    }
    return "Done";
}

说明

  • 加密后:将ByteString形式的密文转为字节数组,再通过Base64编码生成安全字符串,避免二进制数据转字符串时的损坏。
  • 解密前:先将Base64字符串解码回原始字节数组,再传给KMS的解密接口,确保密文完整无误。

内容的提问来源于stack exchange,提问作者BefuddledBarberian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:31:04