Files
cmii-uav-watchdog-project/cmii-uav-watchdog/utils/crypto.go

114 lines
2.2 KiB
Go

package utils
import (
"cmii-uav-watchdog-common/models"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"io"
)
// Encrypt 加密字符串
func Encrypt(plaintext string, key string) (string, error) {
// 创建hash
hasher := sha256.New()
hasher.Write([]byte(key))
keyBytes := hasher.Sum(nil)
// 创建cipher
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
// 创建gcm
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 创建nonce
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 加密
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
// 编码为base64
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// Decrypt 解密字符串
func Decrypt(encrypted string, key string) (string, error) {
// 解码base64
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return "", err
}
// 创建hash
hasher := sha256.New()
hasher.Write([]byte(key))
keyBytes := hasher.Sum(nil)
// 创建cipher
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
// 创建gcm
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 检查长度
if len(ciphertext) < gcm.NonceSize() {
return "", errors.New("密文太短")
}
// 分离nonce和密文
nonce, ciphertext := ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():]
// 解密
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}
// EncryptHostInfo 加密主机信息
func EncryptHostInfo(hostInfo models.HostInfo) (string, error) {
// 序列化主机信息
data, err := json.Marshal(hostInfo)
if err != nil {
return "", err
}
// 计算SHA256作为统一标识
hasher := sha256.New()
hasher.Write(data)
hash := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
return hash, nil
}
// GenerateHostKey 生成主机唯一标识
func GenerateHostKey(hostInfo models.HostInfo) string {
// 序列化主机信息
key := hostInfo.UUID
if key == "" {
key = hostInfo.MAC
}
return key
}