102 lines
2.2 KiB
Go
102 lines
2.2 KiB
Go
package utils
|
||
|
||
import (
|
||
"crypto/aes"
|
||
"crypto/cipher"
|
||
"crypto/hmac"
|
||
"crypto/rand"
|
||
"crypto/sha256"
|
||
"encoding/base64"
|
||
"encoding/hex"
|
||
"io"
|
||
)
|
||
|
||
// Encrypt 加密函数
|
||
func Encrypt(text, key string) (string, error) {
|
||
plaintext := []byte(text)
|
||
hashedKey := hashKey(key)
|
||
|
||
// 创建一个新的 AES cipher.Block
|
||
block, err := aes.NewCipher(hashedKey)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
// 使用 GCM 模式加密
|
||
aesGCM, err := cipher.NewGCM(block)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
nonce := make([]byte, aesGCM.NonceSize())
|
||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||
return "", err
|
||
}
|
||
|
||
// 加密数据
|
||
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
|
||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||
}
|
||
|
||
// Decrypt 解密函数
|
||
func Decrypt(cryptoText, key string) (string, error) {
|
||
ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)
|
||
hashedKey := hashKey(key)
|
||
|
||
// 创建一个新的 AES cipher.Block
|
||
block, err := aes.NewCipher(hashedKey)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
// 使用 GCM 模式解密
|
||
aesGCM, err := cipher.NewGCM(block)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
nonceSize := aesGCM.NonceSize()
|
||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||
|
||
// 解密数据
|
||
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
return string(plaintext), nil
|
||
}
|
||
|
||
// HashString 使用SHA256算法对字符串进行哈希加密
|
||
func HashString(s string) string {
|
||
// 创建一个新的SHA256哈希实例
|
||
hasher := sha256.New()
|
||
|
||
// 写入要哈希的字符串的字节
|
||
hasher.Write([]byte(s))
|
||
|
||
// 获取哈希结果的字节切片
|
||
hashBytes := hasher.Sum(nil)
|
||
|
||
// 将字节切片转换成十六进制字符串表示
|
||
s = hex.EncodeToString(hashBytes)
|
||
|
||
return s
|
||
}
|
||
|
||
// HmacSHA256 计算 HMAC-SHA256 签名
|
||
func HmacSHA256(data string, key string) string {
|
||
// 创建新的 HMAC 使用 SHA256 哈希函数
|
||
h := hmac.New(sha256.New, []byte(key))
|
||
// 写入数据
|
||
h.Write([]byte(data))
|
||
// 计算 HMAC-SHA256 并返回其字节切片
|
||
return hex.EncodeToString(h.Sum(nil))
|
||
}
|
||
|
||
// 将任意长度的密钥转换为适合 AES 的长度(32 字节)
|
||
func hashKey(key string) []byte {
|
||
hash := sha256.Sum256([]byte(key))
|
||
return hash[:]
|
||
}
|