100 lines
2.7 KiB
Go
100 lines
2.7 KiB
Go
package util
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// EncryptAESGCM AES-GCM 加密:输出 nonce(12B) || 密文+tag。
|
|
// key 长度须为 16/24/32 字节(AES-128/192/256)。
|
|
func EncryptAESGCM(key, plaintext []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, fmt.Errorf("util: 生成 nonce 失败: %w", err)
|
|
}
|
|
return gcm.Seal(nonce, nonce, plaintext, nil), nil
|
|
}
|
|
|
|
// DecryptAESGCM 解密 EncryptAESGCM 的输出;密文被篡改时返回错误(GCM 认证)。
|
|
func DecryptAESGCM(key, data []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ns := gcm.NonceSize()
|
|
if len(data) < ns+gcm.Overhead() {
|
|
return nil, errors.New("util: 密文长度非法")
|
|
}
|
|
plaintext, err := gcm.Open(nil, data[:ns], data[ns:], nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("util: 解密失败(密钥错误或密文被篡改): %w", err)
|
|
}
|
|
return plaintext, nil
|
|
}
|
|
|
|
// DeriveKey 由口令派生 32 字节 AES-256 密钥(SHA-256)。
|
|
// 用于从配置口令(如 log.file 中的 secret)得到可用密钥。
|
|
func DeriveKey(passphrase string) []byte {
|
|
h := sha256.Sum256([]byte(passphrase))
|
|
return h[:]
|
|
}
|
|
|
|
// EncryptSecret 便捷封装:口令派生密钥 → AES-GCM → base64(用于 API 密钥落库)。
|
|
func EncryptSecret(passphrase, plaintext string) (string, error) {
|
|
out, err := EncryptAESGCM(DeriveKey(passphrase), []byte(plaintext))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(out), nil
|
|
}
|
|
|
|
// DecryptSecret 解密 EncryptSecret 的输出。
|
|
func DecryptSecret(passphrase, encoded string) (string, error) {
|
|
raw, err := base64.StdEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return "", fmt.Errorf("util: base64 解码失败: %w", err)
|
|
}
|
|
out, err := DecryptAESGCM(DeriveKey(passphrase), raw)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(out), nil
|
|
}
|
|
|
|
// RandomHex 生成 n 字节随机数的十六进制串(2n 字符),用于 API 密钥/令牌生成。
|
|
func RandomHex(n int) (string, error) {
|
|
if n <= 0 {
|
|
return "", errors.New("util: n 必须大于 0")
|
|
}
|
|
b := make([]byte, n)
|
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(b), nil
|
|
}
|
|
|
|
// newGCM 构造 AES-GCM(校验密钥长度)。
|
|
func newGCM(key []byte) (cipher.AEAD, error) {
|
|
switch len(key) {
|
|
case 16, 24, 32:
|
|
default:
|
|
return nil, fmt.Errorf("util: AES 密钥长度非法 %d(须 16/24/32 字节)", len(key))
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cipher.NewGCM(block)
|
|
}
|