63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
var EncryptionKey = ")ZLxR6X@h5tYGhkwin<j"
|
|
|
|
// use sha256 to get 32 bytes key
|
|
func getAESKey(key string) []byte {
|
|
selfSecretKey := os.Getenv("ENCRYPTION_KEY")
|
|
if selfSecretKey != "" {
|
|
key = selfSecretKey
|
|
} else {
|
|
key = EncryptionKey
|
|
}
|
|
hash := sha256.Sum256([]byte(key))
|
|
return hash[:]
|
|
}
|
|
|
|
func Encrypt(plaintext, secret string) (string, error) {
|
|
key := getAESKey(secret)
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
|
|
iv := ciphertext[:aes.BlockSize]
|
|
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
stream := cipher.NewCFBEncrypter(block, iv)
|
|
stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))
|
|
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
|
}
|
|
|
|
func Decrypt(encryptedText, secret string) (string, error) {
|
|
key := getAESKey(secret)
|
|
ciphertext, err := base64.StdEncoding.DecodeString(encryptedText)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(ciphertext) < aes.BlockSize {
|
|
return "", errors.New("the ciphertext is too short")
|
|
}
|
|
iv := ciphertext[:aes.BlockSize]
|
|
ciphertext = ciphertext[aes.BlockSize:]
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
stream := cipher.NewCFBDecrypter(block, iv)
|
|
stream.XORKeyStream(ciphertext, ciphertext)
|
|
return string(ciphertext), nil
|
|
}
|