Last active
April 1, 2019 02:26
-
-
Save sle-c/c82c8df2b3bbb4aa6cc9c9fd85b6b6a7 to your computer and use it in GitHub Desktop.
Decrypt 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" | |
) | |
// 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