72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
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"
|
|
}
|