globaldatanetmenu

.Using AWS KMS with golang

Mar 25th 2020-2 min read

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

globaldatanetCloud Development, Optimization & Automation

.Navigation

.Social

  • follow globaldatanet on instagram
  • follow globaldatanet on facebook
  • follow globaldatanet on twitter
  • follow globaldatanet on linkendin
  • follow globaldatanet on twitch
  •  listen to our serverless world podcast
  • follow globaldatanet's tech rss feed
  • follow globaldatanet at github
© 2024 by globaldatanet. All Right Reserved
Your privacy is important to us!

We use cookies on our website. Some of them are essential,while others help us to improve our online offer.
You can find more information in our Privacy policy