Created
April 1, 2019 02:26
-
-
Save sle-c/8b1778405ce379ec66aa1666393259bf to your computer and use it in GitHub Desktop.
Encrypt text using AES256 GCM in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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