Skip to content

Instantly share code, notes, and snippets.

@sle-c
Created April 1, 2019 02:26
Show Gist options
  • Save sle-c/8b1778405ce379ec66aa1666393259bf to your computer and use it in GitHub Desktop.
Save sle-c/8b1778405ce379ec66aa1666393259bf to your computer and use it in GitHub Desktop.
Encrypt text using AES256 GCM in golang
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"os"
)
// Encrypt will encrypt a raw string to
// an encrypted value
// an encrypted value has an IV (nonce) + actual encrypted value
// when we decrypt, we only decrypt the latter part
func Encrypt(key []byte) ([]byte, error) {
secretKey := getSecret()
block, err := aes.NewCipher(secretKey)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
iv := make([]byte, aesgcm.NonceSize())
if _, err := rand.Read(iv); err != nil {
return nil, err
}
ciphertext := aesgcm.Seal(iv, iv, key, nil)
return ciphertext, nil
}
func getSecret() []byte {
secret := os.Getenv("SECRET")
if secret == "" {
panic("Error: Must provide a secret key under env variable SECRET")
}
secretbite, err := hex.DecodeString(secret)
if err != nil {
// probably malform secret, panic out
panic(err)
}
return secretbite
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment