AWS KMS does a great job providing the necessary key infrastructure to encrypt and decrypt data. Today we will show you how you can use the AWS SKD for golang to encrypt and decrypt data.
First we need to import the relevant SDK packages.
import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kms" )
After importing the packages create a new kms client.
sess, _ := session.NewSession(&aws.Config{ Region: aws.String("eu-central-1")}, ) svc := kms.New(sess)
Now you can start encrypting your data. Define the key ID of your CMK and enter some data to encrypt. Be aware that the aws golang sdk requires binary data as Plaintext input.
const keyID = "alias/tempKey" const myPassword = "super-secret" inputEncrypt := &kms.EncryptInput{ KeyId: aws.String(keyID), Plaintext: []byte(myPassword), } respEncrypt, _ := svc.Encrypt(inputEncrypt) fmt.Println(respEncrypt.CiphertextBlob)
After successfully encrypting our data let's do it the other way around now. The output is again a binary blon that neesds to be converted.
inputDecrypt := &kms.DecryptInput{ CiphertextBlob: respEncrypt.CiphertextBlob, } respDecrypt, _ := svc.Decrypt(inputDecrypt) fmt.Println(string(respDecrypt.Plaintext))
And that's it! Happy encrypting everyone. :)
The example code can be found here: