Using AWS KMS with golang

 
 

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.

Prerequsites

  1. In this example we are using Custom Master Key with the name tempKey, located in the eu-central-1 region. Make sure you have created that key before you try this sample code.
  2. For authentication we are using exported credentials via environment variables. Take a look on how to achieve that with aws-vault.

Import the AWS SDK

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"
)

Setup a kms client

After importing the packages create a new kms client.

  sess, _ := session.NewSession(&aws.Config{
    Region: aws.String("eu-central-1")},
  )

  svc := kms.New(sess)

Encrypt data

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)

Decrypt data

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. :)

Github

The example code can be found here:

Github repository



      

Tasks that require root user

It is AWS best practice to not use the root user. However, there are certain Tasks which requires root credentials.

 

Oct 22nd 2020

 

David Krohn

CloudFormation Best Practices

Recommendations that can help you to use CloudFormation more effectively and securely throughout its entire workflow.

 

Oct 20th 2020

 

David Krohn

Share your ACM Private CA cross-account

How to automate AWS RAM to share your ACM Private CA cross-account

 

Sep 3rd 2020

 

David Krohn