I want to encrypt/decrypt some sensitive data in a Google Cloud project with several AppEngine services. I enabled the Cloud KMS API and, via IAM, added the role "Cloud KMS CryptoKey Encrypter/Decrypter" to the App Engine service account({projectId}@appspot.gserviceaccount.com
).
Then, I created a ring (my-ring
) and a key within the ring (my-key
) accepting the default rotating policy (90days). So I have a key like "projects/{my-project-id}/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key"
I downloaded the App service account json credentials so I can debug the code locally. GOOGLE_APPLICATION_CREDENTIALS
environment variables points to the downloaded file.
When I try to encrypt a message I get the following error: {"error":"invalid_grant","error_description":"Invalid grant: account not found"}
My Go code looks as follows:
func encrypt(plainText []byte) (string, error) {
ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return "", err
}
req := &kmspb.EncryptRequest{Name: variables.EncryptionKey, Plaintext: plainText}
result, err := client.Encrypt(ctx, req)
if err != nil {
fmt.Println(fmt.Errorf("encryption error %s", err))
return "", err
}
return base64.URLEncoding.EncodeToString(result.Ciphertext), nil
}
I don't know what I'm doing wrong.