InvalidCiphertextException when decrypt AWL Lambda environment variable using AWS go sdk

Viewed 125

I'm stuck on this issue for days and have tried all the methods I can find online. I am trying to decrypt (using AWS go sdk) the AWS lambda environment variable encrypted with KMS. I encrypted the env variables in transit and at rest using the same KMS key. Screenshot of environment variables encryption

I had also added the policy to lambda function to allow it to have permission to decrypt the variables. The attached policy looks like the below:

    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "kms:*",
        "Resource": "arn:aws:kms:us-west-2:602487775829:key/f91a9f1a-9b53-4544-xxxxxxxx",
        "Condition": {
            "StringEquals": {
                "kms:EncryptionContext:LambdaFunctionName": "eLead"
            }
        }
    }
}

And here is my Go code snippet for decrypting the variables(KeyId is not necessary for decrypting, I added it just to ensure it uses the same KMS key to encrypt and decrypt):

import (
    "os"
    "context"
    "encoding/base64"
    "github.com/aws/aws-sdk-go-v2/service/kms"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go-v2/config"
)
var API_key = os.Getenv("API_key")    
var API_Secret = os.Getenv("API_Secret")    

func Handler(ctx context.Context) error {

    cfg, err := config.LoadDefaultConfig(context.TODO(),config.WithRegion("us-west-2"))
    API_key_blob, err := base64.StdEncoding.DecodeString(API_key)
    API_Secret_blob, err := base64.StdEncoding.DecodeString(API_Secret)
    keyID := "arn:aws:kms:us-west-2:602487775829:key/f91a9f1a-9b53-4544-a05b-xxxxxx"
    API_key_result, err := kmsClient.Decrypt(context.TODO(),  &kms.DecryptInput{
        CiphertextBlob: API_key_blob,
        KeyId:aws.String(keyID),
    })
    API_Secret_result, err := kmsClient.Decrypt(context.TODO(),&kms.DecryptInput{
        CiphertextBlob: API_Secret_blob,
        KeyId:aws.String(keyID),
    })

    if err != nil {
        fmt.Println("Got error decrypting data: ", err)
        return err
    }

func main() {
    lambda.Start(Handler)
}

The error message is:

Got error decrypting data:  operation error KMS: Decrypt, https response error StatusCode: 400, RequestID: 629a64b2-ce53-46ad-88fb-1f6ac684919e, InvalidCiphertextException:

I don't understand what else can cause this error.
Any suggestion would help! Thanks!

0 Answers
Related