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

使用Golang解密AWS KMS加密代码时遇InvalidCiphertextException错误

解决AWS KMS解密InvalidCiphertextException错误

问题背景

从Cognito UserPool获取加密的Code值,使用Go代码调用AWS KMS的Decrypt接口时,抛出InvalidCiphertextException错误,HTTP状态码400。

错误日志

operation error KMS: Decrypt, https response error StatusCode: 400, RequestID: 9e69224b-7c29-4e89-9d75-a7aa3b5f077a, InvalidCiphertextException: 

原代码片段

ciphertextBlob, err := base64.StdEncoding.DecodeString(event.Request.Code)
if err != nil {
    fmt.Println("Error decoding ciphertext:", err)
}
log.Println("ciphertextBlob--> ", ciphertextBlob)

input := &kms.DecryptInput{
    CiphertextBlob: ciphertextBlob,
    KeyId:          aws.String(KMS_KEY_ID),
    DryRun:         aws.Bool(true),
}

cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(REGION_NAME))
if err != nil {
    log.Fatalf("unable to load SDK config, %v", err)
}

svc := kms.NewFromConfig(cfg)
result, err := svc.Decrypt(ctx, input)

pretty.Println("result--> ", result)
log.Println("err--> ", err)

密文示例:

"AYADeOIZyUqkW5s7WXfThDn8/hgAggACABVhd3MtY3J5cHRvLXB1YmxpYy1rZXkAREEwZ2x4ZCsyODJmK1lxSXV5MEpnTTRyWDJTd0poeWM5WVM0ZzhmWmphczNTem5TT0xkQzV1S1J2bkFPSnlzc1FKZz09AAt1c2VycG9vbC1pZAAUZXUtc291dGgtMV9n="

排查与修复步骤

  • 移除DryRun参数:DryRun仅用于验证权限,不会执行实际解密操作,保留该参数会导致请求无法正常完成解密,直接删除这个字段。
  • 不要手动指定KeyId:Cognito生成的密文已经包含了密钥标识信息,KMS会自动识别对应的密钥,手动指定KeyId可能导致密钥不匹配,引发错误。
  • 完善错误处理:base64解码失败时,当前代码仅打印日志继续执行,会传递无效的密文给KMS,需在解码出错时终止流程并返回错误。
  • 验证密文完整性:确认event.Request.Code是Cognito返回的完整密文,示例中的密文带有引号,需要先去除再解码。

修改后的代码示例

import "strings"

// ...

ciphertextBlob, err := base64.StdEncoding.DecodeString(strings.Trim(event.Request.Code, "\"")) // 去除密文两端的引号
if err != nil {
    log.Fatalf("Failed to decode ciphertext: %v", err) // 解码失败直接终止
}
log.Println("ciphertextBlob--> ", ciphertextBlob)

input := &kms.DecryptInput{
    CiphertextBlob: ciphertextBlob,
    // 移除KeyId和DryRun参数
}

cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(REGION_NAME))
if err != nil {
    log.Fatalf("unable to load SDK config, %v", err)
}

svc := kms.NewFromConfig(cfg)
result, err := svc.Decrypt(ctx, input)

if err != nil {
    log.Fatalf("Decrypt failed: %v", err)
}
pretty.Println("result--> ", result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:00:02