email/utils/passphrase.go

60 lines
1.4 KiB
Go
Raw Permalink Normal View History

2022-11-23 02:50:34 +00:00
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"io"
)
func GeneratePassphrase(key string) string {
hash := md5.New()
hash.Write([]byte(key))
return hex.EncodeToString(hash.Sum(nil))
}
func HashWithPassphrase(data []byte, key string) string {
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
func ASCEncrypt(data []byte, passphrase string) (string, error) {
block, _ := aes.NewCipher([]byte(GeneratePassphrase(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func ASCDecrypt(msg, passphrase string) (string, error) {
data, err := base64.StdEncoding.DecodeString(msg)
key := []byte(GeneratePassphrase(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}