[🚀] add crypto pkg

This commit is contained in:
2026-01-21 16:40:26 +08:00
parent 424ad78a7e
commit 078967c601
5 changed files with 283 additions and 0 deletions

71
pkg/crypto/aes.go Normal file
View File

@@ -0,0 +1,71 @@
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
)
// AESEncryptor AES-GCM加密器
type AESEncryptor struct {
key []byte
}
// NewAESEncryptor 创建AES加密器
func NewAESEncryptor(key string) (*AESEncryptor, error) {
// 使用SHA256生成32字节密钥
hash := sha256.Sum256([]byte(key))
return &AESEncryptor{key: hash[:]}, nil
}
func (e *AESEncryptor) Encrypt(plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(e.key)
if err != nil {
return nil, fmt.Errorf("创建cipher失败: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("创建GCM失败: %w", err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("生成nonce失败: %w", err)
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
func (e *AESEncryptor) Decrypt(ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(e.key)
if err != nil {
return nil, fmt.Errorf("创建cipher失败: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("创建GCM失败: %w", err)
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("密文长度不足")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("解密失败: %w", err)
}
return plaintext, nil
}
func (e *AESEncryptor) Name() string {
return "AES-GCM-256"
}