100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
var (
|
|
// 默认密钥(实际应用中应该从配置文件或环境变量读取)
|
|
// AES-256 需要 32 字节密钥
|
|
// "go-desk-db-cli-key-32bytes123456" = 32 bytes
|
|
defaultKey = []byte("go-desk-db-cli-key-32bytes123456") // 32 bytes for AES-256
|
|
)
|
|
|
|
func init() {
|
|
// 验证密钥长度
|
|
if len(defaultKey) != 32 {
|
|
panic(fmt.Sprintf("AES-256 密钥长度必须为 32 字节,当前为 %d 字节", len(defaultKey)))
|
|
}
|
|
}
|
|
|
|
// EncryptPassword 加密密码
|
|
func EncryptPassword(password string) (string, error) {
|
|
if password == "" {
|
|
return "", nil
|
|
}
|
|
|
|
block, err := aes.NewCipher(defaultKey)
|
|
if err != nil {
|
|
return "", fmt.Errorf("创建加密器失败: %v", err)
|
|
}
|
|
|
|
// 使用 GCM 模式
|
|
aesGCM, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", fmt.Errorf("创建 GCM 失败: %v", err)
|
|
}
|
|
|
|
// 生成随机 nonce
|
|
nonce := make([]byte, aesGCM.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return "", fmt.Errorf("生成 nonce 失败: %v", err)
|
|
}
|
|
|
|
// 加密
|
|
ciphertext := aesGCM.Seal(nonce, nonce, []byte(password), nil)
|
|
|
|
// Base64 编码
|
|
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
|
}
|
|
|
|
// DecryptPassword 解密密码
|
|
func DecryptPassword(encryptedPassword string) (string, error) {
|
|
if encryptedPassword == "" {
|
|
return "", nil
|
|
}
|
|
|
|
// 如果加密字符串为空或格式不正确,返回空字符串
|
|
if len(encryptedPassword) < 10 {
|
|
return "", nil
|
|
}
|
|
|
|
// Base64 解码
|
|
ciphertext, err := base64.StdEncoding.DecodeString(encryptedPassword)
|
|
if err != nil {
|
|
return "", fmt.Errorf("解码失败: %v", err)
|
|
}
|
|
|
|
block, err := aes.NewCipher(defaultKey)
|
|
if err != nil {
|
|
return "", fmt.Errorf("创建解密器失败: %v", err)
|
|
}
|
|
|
|
// 使用 GCM 模式
|
|
aesGCM, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", fmt.Errorf("创建 GCM 失败: %v", err)
|
|
}
|
|
|
|
// 提取 nonce
|
|
nonceSize := aesGCM.NonceSize()
|
|
if len(ciphertext) < nonceSize {
|
|
return "", fmt.Errorf("密文长度不足")
|
|
}
|
|
|
|
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
|
|
|
// 解密
|
|
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("解密失败: %v", err)
|
|
}
|
|
|
|
return string(plaintext), nil
|
|
}
|