Skip to content

Instantly share code, notes, and snippets.

@sle-c
Last active April 1, 2019 02:26
Show Gist options
  • Save sle-c/c82c8df2b3bbb4aa6cc9c9fd85b6b6a7 to your computer and use it in GitHub Desktop.
Save sle-c/c82c8df2b3bbb4aa6cc9c9fd85b6b6a7 to your computer and use it in GitHub Desktop.
Decrypt text using AES256 GCM in golang
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"os"
)
// Decrypt will return the original value of the encrypted string
func Decrypt(encryptedKey []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
}
if len(encryptedKey) < aesgcm.NonceSize() {
// worth panicking when encrypted key is bad
panic("Malformed encrypted key")
}
return aesgcm.Open(
nil,
encryptedKey[:aesgcm.NonceSize()],
encryptedKey[aesgcm.NonceSize():],
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