This commit is contained in:
2024-07-02 17:37:50 +08:00
parent c87c7076df
commit 53e72e1ee2
35 changed files with 1813 additions and 60 deletions
+90
View File
@@ -0,0 +1,90 @@
package utils
import (
"crypto/aes"
"crypto/cipher"
"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
}
// 将任意长度的密钥转换为适合 AES 的长度(32 字节)
func hashKey(key string) []byte {
hash := sha256.Sum256([]byte(key))
return hash[:]
}
+8
View File
@@ -20,3 +20,11 @@ func AddOssDomain(url string) string {
}
return config.C.Oss.OssCustomDomainName + url
}
// AddDomain 增加地址中的前缀
func AddDomain(url string) string {
if url == "" {
return ""
}
return config.C.Domain + "/share/" + url
}