101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
package utils
|
||
|
||
import (
|
||
"crypto/aes"
|
||
"crypto/cipher"
|
||
"crypto/rand"
|
||
"crypto/sha256"
|
||
"encoding/base64"
|
||
"encoding/hex"
|
||
"fmt"
|
||
"io"
|
||
mathRand "math/rand"
|
||
"time"
|
||
)
|
||
|
||
// 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
|
||
}
|
||
|
||
// 将任意长度的密钥转换为适合 AES 的长度(32 字节)
|
||
func hashKey(key string) []byte {
|
||
hash := sha256.Sum256([]byte(key))
|
||
return hash[:]
|
||
}
|
||
|
||
// GenerateUniqueCode 生成6位数唯一码
|
||
func GenerateUniqueCode() string {
|
||
mathRand.Seed(time.Now().UnixNano())
|
||
code := fmt.Sprintf("%06d", mathRand.Intn(999999))
|
||
return code
|
||
}
|