完善不同加密方法的使用
This commit is contained in:
+342
-324
@@ -1,7 +1,20 @@
|
||||
// Package aesx 提供 AES 分组密码的加解密封装,支持 ECB/CBC/CFB/OFB/CTR 与 GCM。
|
||||
//
|
||||
// AES 是当前使用最广泛的对称分组密码:分组长度固定 16 字节,密钥长度可以是
|
||||
// 16(AES-128)、24(AES-192)或 32(AES-256)字节。新代码建议使用 AES-256。
|
||||
//
|
||||
// # 模式选择建议
|
||||
//
|
||||
// - AES-GCM:带认证的加密(AEAD),**首选**,同时保证机密性与完整性;
|
||||
// - AES-CTR / CFB / OFB:流式模式,**不提供完整性保护**,密文比特可被随意翻转;
|
||||
// - AES-CBC:需要填充,不提供完整性保护,且存在 padding oracle 风险;
|
||||
// - AES-ECB:**不具备语义安全性**,相同明文块会产生相同密文块,仅用于兼容旧系统。
|
||||
//
|
||||
// 除 GCM 之外的所有模式都必须另行配合消息认证码(例如 HMAC)使用,并采用
|
||||
// 「先加密后认证」(Encrypt-then-MAC)的组合方式,否则无法发现密文篡改。
|
||||
package aesx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
@@ -9,363 +22,368 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"code.yun.ink/pkg/encryptx/cipherx"
|
||||
)
|
||||
|
||||
// AES-256-ECB 加密,返回大写的十六进制字符串
|
||||
func EncryptECBHex(input, key string) (string, error) {
|
||||
// 创建AES加密器
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
const (
|
||||
// KeySize128 是 AES-128 的密钥长度(字节)。
|
||||
KeySize128 = 16
|
||||
// KeySize192 是 AES-192 的密钥长度(字节)。
|
||||
KeySize192 = 24
|
||||
// KeySize256 是 AES-256 的密钥长度(字节)。
|
||||
KeySize256 = 32
|
||||
// BlockSize 是 AES 的分组长度(字节)。
|
||||
BlockSize = aes.BlockSize
|
||||
// GCMNonceSize 是 GCM 推荐使用的 nonce 长度(字节)。
|
||||
//
|
||||
// 12 字节是与 GCM 设计匹配的「标准」长度:其他长度会先在内部做 GHASH 派生,
|
||||
// 既慢又更容易因实现差异导致互通问题。
|
||||
GCMNonceSize = 12
|
||||
// GCMTagSize 是 GCM 认证标签的长度(字节)。
|
||||
GCMTagSize = 16
|
||||
)
|
||||
|
||||
// 对输入数据进行PKCS7填充
|
||||
paddedInput := PKCS7Padding([]byte(input), block.BlockSize())
|
||||
// GCM 相关的错误定义。
|
||||
var (
|
||||
// ErrInvalidNonceSize 表示 GCM 的 nonce 长度不等于 GCMNonceSize。
|
||||
ErrInvalidNonceSize = errors.New("aesx: invalid GCM nonce size")
|
||||
// ErrCiphertextTooShort 表示密文长度不足以容纳认证标签。
|
||||
ErrCiphertextTooShort = errors.New("aesx: ciphertext is shorter than the GCM tag")
|
||||
// ErrAuthenticationFailed 表示 GCM 认证失败:密文、nonce 或 AAD 被篡改,
|
||||
// 或密钥错误。解密结果不可信,调用方不得使用任何返回的明文。
|
||||
ErrAuthenticationFailed = errors.New("aesx: GCM authentication failed")
|
||||
)
|
||||
|
||||
// ECB模式加密
|
||||
encrypted := make([]byte, len(paddedInput))
|
||||
for i := 0; i < len(paddedInput); i += aes.BlockSize {
|
||||
block.Encrypt(encrypted[i:i+aes.BlockSize], paddedInput[i:i+aes.BlockSize])
|
||||
}
|
||||
// Suite 绑定 AES 的分组构造方式与合法密钥长度,模式实现由 cipherx 提供。
|
||||
//
|
||||
// 导出它是为了让调用方能够以统一方式驱动任意模式(例如由配置决定模式时),
|
||||
// 而无需在本包与 cipherx 之间写 switch。
|
||||
var Suite = cipherx.NewSuite("AES", aes.NewCipher, BlockSize, KeySize128, KeySize192, KeySize256)
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(encrypted)
|
||||
return strings.ToUpper(result), nil
|
||||
// ValidKeySize 报告 keySize 是否为合法的 AES 密钥长度。
|
||||
func ValidKeySize(keySize int) bool {
|
||||
return keySize == KeySize128 || keySize == KeySize192 || keySize == KeySize256
|
||||
}
|
||||
|
||||
// AES-256-ECB 解密,输入大写的十六进制字符串
|
||||
func DecryptECBHex(encryptedHex, key string) (string, error) {
|
||||
encrypted, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
// GenerateKey 用 crypto/rand 生成指定长度的 AES 密钥。
|
||||
//
|
||||
// keySize 必须是 16、24 或 32;调用方应妥善保存返回值,密钥一旦丢失或泄漏,
|
||||
// 已加密的数据将无法保护。
|
||||
func GenerateKey(keySize int) ([]byte, error) {
|
||||
if !ValidKeySize(keySize) {
|
||||
return nil, fmt.Errorf("aesx: 密钥长度 %d 非法, 允许 16/24/32: %w", keySize, cipherx.ErrInvalidKeySize)
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("创建AES解密器失败: %v", err)
|
||||
key := make([]byte, keySize)
|
||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
||||
return nil, fmt.Errorf("aesx: 生成密钥失败: %w", err)
|
||||
}
|
||||
|
||||
// ECB模式解密
|
||||
decrypted := make([]byte, len(encrypted))
|
||||
for i := 0; i < len(encrypted); i += aes.BlockSize {
|
||||
block.Decrypt(decrypted[i:i+aes.BlockSize], encrypted[i:i+aes.BlockSize])
|
||||
}
|
||||
|
||||
// 去除PKCS7填充
|
||||
unpaddedData, err := PKCS7UnPadding(decrypted)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("去除填充失败: %v", err)
|
||||
}
|
||||
return string(unpaddedData), nil
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// AES-256-CBC 加密
|
||||
func EncryptCBCHex(plaintext, key string) (string, error) {
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
// GenerateKeyHex 生成 AES 密钥并以十六进制字符串返回,便于写入配置文件。
|
||||
//
|
||||
// 注意:返回值是**编码后的文本**,不能直接当密钥使用。读回后必须先解码
|
||||
// (encoding/hex 的 DecodeString,或本库的 hexx.Decode),再传给 Encrypt/Decrypt;
|
||||
// 直接把字符串当密钥传入会因长度翻倍而被拒绝。
|
||||
func GenerateKeyHex(keySize int) (string, error) {
|
||||
key, err := GenerateKey(keySize)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
blockSize := block.BlockSize()
|
||||
plainBytes := PKCS7Padding([]byte(plaintext), blockSize)
|
||||
|
||||
// 创建密文字节切片,包含IV空间
|
||||
cipherbyte := make([]byte, aes.BlockSize+len(plainBytes))
|
||||
|
||||
// 生成随机IV
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建CBC模式加密器
|
||||
blockMode := cipher.NewCBCEncrypter(block, iv)
|
||||
|
||||
// 加密数据
|
||||
blockMode.CryptBlocks(cipherbyte[aes.BlockSize:], plainBytes)
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(cipherbyte)
|
||||
return strings.ToUpper(result), nil
|
||||
return hex.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// AES-256-CBC 解密
|
||||
func DecryptCBCHex(encryptedHex, key string) (string, error) {
|
||||
cipherbyte, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
// ---- ECB ----
|
||||
//
|
||||
// 警告:ECB 不具备语义安全性,相同的明文分组会产生相同的密文分组,攻击者可以
|
||||
// 借此识别明文中的重复结构与规律。仅为兼容既有系统而提供。
|
||||
|
||||
if len(cipherbyte) < aes.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
cipherbyte = cipherbyte[aes.BlockSize:]
|
||||
if len(cipherbyte)%aes.BlockSize != 0 {
|
||||
return "", errors.New("ciphertext is not a multiple of the block size")
|
||||
}
|
||||
|
||||
blockMode := cipher.NewCBCDecrypter(block, iv)
|
||||
origData := make([]byte, len(cipherbyte))
|
||||
blockMode.CryptBlocks(origData, cipherbyte)
|
||||
origBy, err := PKCS7UnPadding(origData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(origBy), nil
|
||||
// EncryptECB 使用 AES-ECB 加密并做 PKCS#7 填充,返回大写十六进制字符串。
|
||||
func EncryptECB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.ECB, plaintext, key)
|
||||
}
|
||||
|
||||
/*
|
||||
AES CBC 加密
|
||||
key:加密key
|
||||
plaintext:加密明文
|
||||
ciphertext:解密返回字节字符串[ 整型以十六进制方式显示]
|
||||
*/
|
||||
func AESCBCEncrypt(key, plaintext string) (ciphertext string, err error) {
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
padding := aes.BlockSize - (len(plaintext) % aes.BlockSize)
|
||||
padtest := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
plainBytes := append([]byte(plaintext), padtest...)
|
||||
|
||||
cipherbyte := make([]byte, aes.BlockSize+len(plainBytes))
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(cipherbyte[aes.BlockSize:], plainBytes)
|
||||
|
||||
ciphertext = fmt.Sprintf("%x\n", cipherbyte)
|
||||
return
|
||||
// DecryptECB 解密 AES-ECB 密文。
|
||||
func DecryptECB(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.ECB, ciphertext, key)
|
||||
}
|
||||
|
||||
// AES CBC 解码
|
||||
// key:解密key
|
||||
// ciphertext:加密返回的串
|
||||
// plaintext:解密后的字符串
|
||||
func AESCBCDecrypter(key, ciphertext string) (plaintext string, err error) {
|
||||
cipherbyte, _ := hex.DecodeString(ciphertext)
|
||||
keybyte := []byte(key)
|
||||
block, err := aes.NewCipher(keybyte)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(cipherbyte) < aes.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
cipherbyte = cipherbyte[aes.BlockSize:]
|
||||
if len(cipherbyte)%aes.BlockSize != 0 {
|
||||
return "", errors.New("ciphertext is not a multiple of the block size")
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCDecrypter(block, iv)
|
||||
mode.CryptBlocks(cipherbyte, cipherbyte)
|
||||
|
||||
//fmt.Printf("%s\n", ciphertext)
|
||||
plaintext = string(cipherbyte[:])
|
||||
return
|
||||
// EncryptECBHex 与 EncryptECB 相同,返回大写十六进制字符串。
|
||||
func EncryptECBHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.ECB, plaintext, key)
|
||||
}
|
||||
|
||||
// AES GCM 加密
|
||||
// key:加密key
|
||||
// plaintext:加密明文
|
||||
// ciphertext:解密返回字节字符串[ 整型以十六进制方式显示]
|
||||
func EncryptGCM(key, plaintext string) (ciphertext, noncetext string, err error) {
|
||||
plainbyte := []byte(plaintext)
|
||||
keybyte := []byte(key)
|
||||
block, err := aes.NewCipher(keybyte)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
// DecryptECBHex 解密十六进制 AES-ECB 密文,大小写均可。
|
||||
func DecryptECBHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.ECB, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// 由于存在重复的风险,请勿使用给定密钥使用超过2^32个随机值。
|
||||
nonce := make([]byte, 12)
|
||||
// ---- CBC ----
|
||||
|
||||
// EncryptCBC 使用 AES-CBC 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCBC(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CBC, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCBC 解密 AES-CBC 密文(IV 前置格式)。
|
||||
func DecryptCBC(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.CBC, ciphertext, key)
|
||||
}
|
||||
|
||||
// EncryptCBCHex 与 EncryptCBC 相同,返回大写十六进制字符串。
|
||||
func EncryptCBCHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.CBC, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCBCHex 解密十六进制 AES-CBC 密文。
|
||||
func DecryptCBCHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.CBC, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// EncryptCBCWithIV 使用调用方指定的 IV 加密,返回值不含 IV。
|
||||
//
|
||||
// 仅用于与规定了固定 IV 的既有系统互操作;自行管理 IV 时必须保证 IV 随机且
|
||||
// 不可预测,并且在同一密钥下绝不重用。
|
||||
func EncryptCBCWithIV(plaintext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.EncryptWithIV(cipherx.CBC, plaintext, key, iv)
|
||||
}
|
||||
|
||||
// DecryptCBCWithIV 使用调用方指定的 IV 解密。
|
||||
func DecryptCBCWithIV(ciphertext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.DecryptWithIV(cipherx.CBC, ciphertext, key, iv)
|
||||
}
|
||||
|
||||
// ---- CFB ----
|
||||
|
||||
// EncryptCFB 使用 AES-CFB 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCFB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCFB 解密 AES-CFB 密文(IV 前置格式)。
|
||||
func DecryptCFB(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.CFB, ciphertext, key)
|
||||
}
|
||||
|
||||
// EncryptCFBHex 与 EncryptCFB 相同,返回大写十六进制字符串。
|
||||
func EncryptCFBHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.CFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCFBHex 解密十六进制 AES-CFB 密文。
|
||||
func DecryptCFBHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.CFB, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// EncryptCFBWithIV 使用调用方指定的 IV 加密,返回值不含 IV。
|
||||
func EncryptCFBWithIV(plaintext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.EncryptWithIV(cipherx.CFB, plaintext, key, iv)
|
||||
}
|
||||
|
||||
// DecryptCFBWithIV 使用调用方指定的 IV 解密。
|
||||
func DecryptCFBWithIV(ciphertext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.DecryptWithIV(cipherx.CFB, ciphertext, key, iv)
|
||||
}
|
||||
|
||||
// ---- OFB ----
|
||||
|
||||
// EncryptOFB 使用 AES-OFB 加密,随机 IV 前置在密文之前。
|
||||
func EncryptOFB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.OFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptOFB 解密 AES-OFB 密文(IV 前置格式)。
|
||||
func DecryptOFB(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.OFB, ciphertext, key)
|
||||
}
|
||||
|
||||
// EncryptOFBHex 与 EncryptOFB 相同,返回大写十六进制字符串。
|
||||
func EncryptOFBHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.OFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptOFBHex 解密十六进制 AES-OFB 密文。
|
||||
func DecryptOFBHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.OFB, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// EncryptOFBWithIV 使用调用方指定的 IV 加密,返回值不含 IV。
|
||||
func EncryptOFBWithIV(plaintext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.EncryptWithIV(cipherx.OFB, plaintext, key, iv)
|
||||
}
|
||||
|
||||
// DecryptOFBWithIV 使用调用方指定的 IV 解密。
|
||||
func DecryptOFBWithIV(ciphertext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.DecryptWithIV(cipherx.OFB, ciphertext, key, iv)
|
||||
}
|
||||
|
||||
// ---- CTR ----
|
||||
|
||||
// EncryptCTR 使用 AES-CTR 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCTR(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CTR, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCTR 解密 AES-CTR 密文(IV 前置格式)。
|
||||
//
|
||||
// CTR 是对合的:加密与解密是同一个运算,因此本函数与 EncryptCTR 等价。
|
||||
func DecryptCTR(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.CTR, ciphertext, key)
|
||||
}
|
||||
|
||||
// EncryptCTRHex 与 EncryptCTR 相同,返回大写十六进制字符串。
|
||||
func EncryptCTRHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.CTR, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCTRHex 解密十六进制 AES-CTR 密文。
|
||||
func DecryptCTRHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.CTR, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// EncryptCTRWithIV 使用调用方指定的 IV 加密,返回值不含 IV。
|
||||
func EncryptCTRWithIV(plaintext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.EncryptWithIV(cipherx.CTR, plaintext, key, iv)
|
||||
}
|
||||
|
||||
// DecryptCTRWithIV 使用调用方指定的 IV 解密。
|
||||
func DecryptCTRWithIV(ciphertext, key, iv []byte) ([]byte, error) {
|
||||
return Suite.DecryptWithIV(cipherx.CTR, ciphertext, key, iv)
|
||||
}
|
||||
|
||||
// ---- GCM ----
|
||||
//
|
||||
// GCM 是本包唯一提供完整性保护的 AEAD 模式,应作为默认选择。
|
||||
|
||||
func newGCM(key []byte) (cipher.AEAD, error) {
|
||||
block, err := Suite.NewBlock(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("aesx: 创建 GCM 失败: %w", err)
|
||||
}
|
||||
return aead, nil
|
||||
}
|
||||
|
||||
// NewGCMNonce 生成一个随机的 12 字节 GCM nonce。
|
||||
//
|
||||
// nonce 本身无需保密,但**在同一密钥下绝不能重复**:GCM 一旦重用 nonce,
|
||||
// 攻击者即可恢复认证密钥并伪造密文。使用同一个密钥加密超过 2^32 条消息时
|
||||
// 应更换密钥。
|
||||
func NewGCMNonce() ([]byte, error) {
|
||||
nonce := make([]byte, GCMNonceSize)
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", "", err
|
||||
return nil, fmt.Errorf("aesx: 生成 GCM nonce 失败: %w", err)
|
||||
}
|
||||
return nonce, nil
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
// EncryptGCM 使用 AES-GCM 加密,随机生成 nonce 并单独返回。
|
||||
//
|
||||
// aad(附加认证数据)会参与完整性校验但不被加密,可用于绑定协议头、版本号、
|
||||
// 消息 ID 等上下文;不需要时传 nil。密文返回值已包含认证标签。
|
||||
//
|
||||
// 调用方必须把 nonce 与密文一起保存或传输。
|
||||
func EncryptGCM(plaintext, key, aad []byte) (ciphertext, nonce []byte, err error) {
|
||||
aead, err := newGCM(key)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
nonce, err = NewGCMNonce()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return aead.Seal(nil, nonce, plaintext, aad), nonce, nil
|
||||
}
|
||||
|
||||
// EncryptGCMWithNonce 使用调用方提供的 nonce 加密,返回值不含 nonce。
|
||||
//
|
||||
// 仅用于与既有系统互操作。传入的 nonce 必须与密文一同保存,且在同一密钥下
|
||||
// 绝不重复使用。
|
||||
func EncryptGCMWithNonce(plaintext, key, nonce, aad []byte) ([]byte, error) {
|
||||
aead, err := newGCM(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nonce) != aead.NonceSize() {
|
||||
return nil, fmt.Errorf("aesx: GCM nonce 长度 %d, 期望 %d: %w",
|
||||
len(nonce), aead.NonceSize(), ErrInvalidNonceSize)
|
||||
}
|
||||
return aead.Seal(nil, nonce, plaintext, aad), nil
|
||||
}
|
||||
|
||||
// DecryptGCM 使用 AES-GCM 解密并验证完整性。
|
||||
//
|
||||
// 认证失败时返回包装了 ErrAuthenticationFailed 的错误,此时**返回的明文为
|
||||
// nil**,调用方绝不可使用任何部分解密结果。
|
||||
func DecryptGCM(ciphertext, key, nonce, aad []byte) ([]byte, error) {
|
||||
aead, err := newGCM(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nonce) != aead.NonceSize() {
|
||||
return nil, fmt.Errorf("aesx: GCM nonce 长度 %d, 期望 %d: %w",
|
||||
len(nonce), aead.NonceSize(), ErrInvalidNonceSize)
|
||||
}
|
||||
// 长度校验必须在 Open 之前:认证标签至少要占 Overhead 字节。
|
||||
if len(ciphertext) < aead.Overhead() {
|
||||
return nil, fmt.Errorf("aesx: GCM 密文长度 %d 小于认证标签长度 %d: %w",
|
||||
len(ciphertext), aead.Overhead(), ErrCiphertextTooShort)
|
||||
}
|
||||
plaintext, err := aead.Open(nil, nonce, ciphertext, aad)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", ErrAuthenticationFailed, err)
|
||||
}
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// SealGCM 加密并把 nonce 前置在密文中,返回 nonce||密文。
|
||||
//
|
||||
// 单字段存储场景(数据库一个列、一个 token)用这个函数最省事:nonce 随密文
|
||||
// 一起存放,不会漏掉。
|
||||
func SealGCM(plaintext, key, aad []byte) ([]byte, error) {
|
||||
ciphertext, nonce, err := EncryptGCM(plaintext, key, aad)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sealed := make([]byte, 0, len(nonce)+len(ciphertext))
|
||||
sealed = append(sealed, nonce...)
|
||||
sealed = append(sealed, ciphertext...)
|
||||
return sealed, nil
|
||||
}
|
||||
|
||||
// OpenGCM 解密 SealGCM 产生的数据(nonce||密文 格式)。
|
||||
func OpenGCM(sealed, key, aad []byte) ([]byte, error) {
|
||||
if len(sealed) < GCMNonceSize+GCMTagSize {
|
||||
return nil, fmt.Errorf("aesx: 数据长度 %d 不足以容纳 nonce 与认证标签: %w",
|
||||
len(sealed), ErrCiphertextTooShort)
|
||||
}
|
||||
nonce := sealed[:GCMNonceSize]
|
||||
ciphertext := sealed[GCMNonceSize:]
|
||||
return DecryptGCM(ciphertext, key, nonce, aad)
|
||||
}
|
||||
|
||||
// EncryptGCMHex 与 EncryptGCM 相同,但密文与 nonce 均以十六进制字符串返回。
|
||||
func EncryptGCMHex(plaintext, key, aad []byte) (ciphertextHex, nonceHex string, err error) {
|
||||
ciphertext, nonce, err := EncryptGCM(plaintext, key, aad)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
cipherbyte := aesgcm.Seal(nil, nonce, plainbyte, nil)
|
||||
ciphertext = fmt.Sprintf("%x\n", cipherbyte)
|
||||
noncetext = fmt.Sprintf("%x\n", nonce)
|
||||
return
|
||||
return hex.EncodeToString(ciphertext), hex.EncodeToString(nonce), nil
|
||||
}
|
||||
|
||||
// AES GCM 解码
|
||||
// key:解密key
|
||||
// ciphertext:加密返回的串
|
||||
// plaintext:解密后的字符串
|
||||
func DecryptGCM(key, ciphertext, noncetext string) (plaintext string, err error) {
|
||||
cipherbyte, _ := hex.DecodeString(ciphertext)
|
||||
nonce, _ := hex.DecodeString(noncetext)
|
||||
keybyte := []byte(key)
|
||||
block, err := aes.NewCipher(keybyte)
|
||||
// DecryptGCMHex 解密十六进制形式的 GCM 密文与 nonce。
|
||||
func DecryptGCMHex(ciphertextHex, nonceHex string, key, aad []byte) ([]byte, error) {
|
||||
ciphertext, err := hex.DecodeString(ciphertextHex)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, fmt.Errorf("aesx: 密文十六进制解码失败: %w", err)
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
nonce, err := hex.DecodeString(nonceHex)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, fmt.Errorf("aesx: nonce 十六进制解码失败: %w", err)
|
||||
}
|
||||
|
||||
plainbyte, err := aesgcm.Open(nil, nonce, cipherbyte, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
//fmt.Printf("%s\n", ciphertext)
|
||||
plaintext = string(plainbyte[:])
|
||||
return
|
||||
return DecryptGCM(ciphertext, key, nonce, aad)
|
||||
}
|
||||
|
||||
// AES CFB 加密
|
||||
func EncryptCFBHex(plaintext, key string) (string, error) {
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建密文字节切片,包含IV空间
|
||||
cipherbyte := make([]byte, aes.BlockSize+len(plaintext))
|
||||
|
||||
// 生成随机IV
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建CFB模式加密器
|
||||
stream := cipher.NewCFBEncrypter(block, iv)
|
||||
stream.XORKeyStream(cipherbyte[aes.BlockSize:], []byte(plaintext))
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(cipherbyte)
|
||||
return strings.ToUpper(result), nil
|
||||
}
|
||||
|
||||
// AES CFB 解密
|
||||
func DecryptCFBHex(encryptedHex, key string) (string, error) {
|
||||
cipherbyte, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
|
||||
if len(cipherbyte) < aes.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 获取IV
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
cipherbyte = cipherbyte[aes.BlockSize:]
|
||||
|
||||
// 创建CFB模式解密器
|
||||
stream := cipher.NewCFBDecrypter(block, iv)
|
||||
stream.XORKeyStream(cipherbyte, cipherbyte)
|
||||
|
||||
return string(cipherbyte), nil
|
||||
}
|
||||
|
||||
// AES OFB 加密
|
||||
func EncryptOFBHex(plaintext, key string) (string, error) {
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建密文字节切片,包含IV空间
|
||||
cipherbyte := make([]byte, aes.BlockSize+len(plaintext))
|
||||
|
||||
// 生成随机IV
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建OFB模式加密器
|
||||
stream := cipher.NewOFB(block, iv)
|
||||
stream.XORKeyStream(cipherbyte[aes.BlockSize:], []byte(plaintext))
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(cipherbyte)
|
||||
return strings.ToUpper(result), nil
|
||||
}
|
||||
|
||||
// AES OFB 解密
|
||||
func DecryptOFBHex(encryptedHex, key string) (string, error) {
|
||||
cipherbyte, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
|
||||
if len(cipherbyte) < aes.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 获取IV
|
||||
iv := cipherbyte[:aes.BlockSize]
|
||||
cipherbyte = cipherbyte[aes.BlockSize:]
|
||||
|
||||
// 创建OFB模式解密器
|
||||
stream := cipher.NewOFB(block, iv)
|
||||
stream.XORKeyStream(cipherbyte, cipherbyte)
|
||||
|
||||
return string(cipherbyte), nil
|
||||
}
|
||||
|
||||
// PKCS7补码
|
||||
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// 去除PKCS7补码
|
||||
func PKCS7UnPadding(data []byte) ([]byte, error) {
|
||||
length := len(data)
|
||||
if length == 0 {
|
||||
return nil, errors.New("ciphertext is empty")
|
||||
}
|
||||
|
||||
unpadding := int(data[length-1])
|
||||
if unpadding > length || unpadding == 0 {
|
||||
return nil, errors.New("unpadding size is invalid")
|
||||
}
|
||||
|
||||
// 检查填充是否正确
|
||||
for i := length - unpadding; i < length; i++ {
|
||||
if data[i] != byte(unpadding) {
|
||||
return nil, errors.New("invalid padding")
|
||||
}
|
||||
}
|
||||
|
||||
return data[:(length - unpadding)], nil
|
||||
}
|
||||
+439
-78
@@ -1,117 +1,478 @@
|
||||
package aesx_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"code.yun.ink/pkg/encryptx/aesx"
|
||||
"code.yun.ink/pkg/encryptx/cipherx"
|
||||
)
|
||||
|
||||
func TestGCM(t *testing.T) {
|
||||
key := "example key 1234"
|
||||
plaintext := "exampleplaintext"
|
||||
|
||||
// aesx.AesEncrypt(plaintext,key)
|
||||
// aesx.AesDecrypt()
|
||||
|
||||
ciphertext, err := aesx.AESCBCEncrypt(key, plaintext)
|
||||
fmt.Println(ciphertext, err)
|
||||
|
||||
plaintext, err = aesx.AESCBCDecrypter(key, ciphertext)
|
||||
fmt.Println(plaintext, err)
|
||||
///GCM
|
||||
noncetext := ""
|
||||
ciphertext, noncetext, err = aesx.EncryptGCM(key, plaintext)
|
||||
fmt.Println(ciphertext, err)
|
||||
|
||||
plaintext, err = aesx.DecryptGCM(key, ciphertext, noncetext)
|
||||
fmt.Println(plaintext, err)
|
||||
func testKey(t *testing.T, size int) []byte {
|
||||
t.Helper()
|
||||
key, err := aesx.GenerateKey(size)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKey(%d) 失败: %v", size, err)
|
||||
}
|
||||
if len(key) != size {
|
||||
t.Fatalf("GenerateKey(%d) 返回长度 %d", size, len(key))
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func TestECB(t *testing.T) {
|
||||
key := "example key 1234"
|
||||
plaintext := "exampleplaintext"
|
||||
|
||||
// 测试ECB加密和解密
|
||||
encrypted, err := aesx.EncryptECBHex(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("ECB加密失败: %v", err)
|
||||
func TestGenerateKey(t *testing.T) {
|
||||
for _, size := range []int{aesx.KeySize128, aesx.KeySize192, aesx.KeySize256} {
|
||||
key := testKey(t, size)
|
||||
if !aesx.ValidKeySize(len(key)) {
|
||||
t.Errorf("ValidKeySize(%d) = false, 期望 true", len(key))
|
||||
}
|
||||
}
|
||||
fmt.Printf("ECB加密结果: %s\n", encrypted)
|
||||
|
||||
decrypted, err := aesx.DecryptECBHex(encrypted, key)
|
||||
if err != nil {
|
||||
t.Fatalf("ECB解密失败: %v", err)
|
||||
// 非法长度必须被拒绝
|
||||
for _, size := range []int{-1, 0, 1, 15, 17, 31, 33, 64} {
|
||||
if _, err := aesx.GenerateKey(size); err == nil {
|
||||
t.Errorf("GenerateKey(%d) 期望错误, 得到 nil", size)
|
||||
}
|
||||
if aesx.ValidKeySize(size) {
|
||||
t.Errorf("ValidKeySize(%d) = true, 期望 false", size)
|
||||
}
|
||||
}
|
||||
fmt.Printf("ECB解密结果: %s\n", decrypted)
|
||||
|
||||
if decrypted != plaintext {
|
||||
t.Fatalf("ECB解密结果不匹配,原文: %s, 解密结果: %s", plaintext, decrypted)
|
||||
// 两次生成的密钥不得相同
|
||||
k1, _ := aesx.GenerateKey(aesx.KeySize256)
|
||||
k2, _ := aesx.GenerateKey(aesx.KeySize256)
|
||||
if bytes.Equal(k1, k2) {
|
||||
t.Error("两次 GenerateKey 产生了相同密钥")
|
||||
}
|
||||
|
||||
hexKey, err := aesx.GenerateKeyHex(aesx.KeySize256)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKeyHex 失败: %v", err)
|
||||
}
|
||||
if len(hexKey) != 64 {
|
||||
t.Errorf("GenerateKeyHex(32) 长度 = %d, 期望 64", len(hexKey))
|
||||
}
|
||||
if _, err := aesx.GenerateKeyHex(7); err == nil {
|
||||
t.Error("GenerateKeyHex(7) 期望错误")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCBC(t *testing.T) {
|
||||
key := "example key 1234"
|
||||
plaintext := "exampleplaintext"
|
||||
// TestKeySizeValidation 是 P0-2 的回归测试。
|
||||
//
|
||||
// 旧实现的 GenerateKey 返回十六进制字符串(32 字节 → 64 字符),而加密函数把
|
||||
// 入参直接当原始密钥字节用,导致「生成密钥 → 加密」这条最基本的路径必然失败
|
||||
// (invalid key size 64)。现在密钥统一为 []byte,两者天然一致。
|
||||
func TestKeySizeValidation(t *testing.T) {
|
||||
plaintext := []byte("hello world")
|
||||
|
||||
// 测试CBC加密和解密
|
||||
encrypted, err := aesx.EncryptCBCHex(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CBC加密失败: %v", err)
|
||||
for _, wrongLen := range []int{5, 15, 17, 31, 33, 64} {
|
||||
key := bytes.Repeat([]byte{0x01}, wrongLen)
|
||||
if _, err := aesx.EncryptCBC(plaintext, key); !errors.Is(err, cipherx.ErrInvalidKeySize) {
|
||||
t.Errorf("密钥长度 %d: 期望 ErrInvalidKeySize, 得到 %v", wrongLen, err)
|
||||
}
|
||||
}
|
||||
fmt.Printf("CBC加密结果: %s\n", encrypted)
|
||||
|
||||
decrypted, err := aesx.DecryptCBCHex(encrypted, key)
|
||||
// GenerateKey 的返回值必须能直接用于加密(旧实现做不到)
|
||||
key, err := aesx.GenerateKey(aesx.KeySize256)
|
||||
if err != nil {
|
||||
t.Fatalf("CBC解密失败: %v", err)
|
||||
t.Fatalf("GenerateKey 失败: %v", err)
|
||||
}
|
||||
fmt.Printf("CBC解密结果: %s\n", decrypted)
|
||||
|
||||
if decrypted != plaintext {
|
||||
t.Fatalf("CBC解密结果不匹配,原文: %s, 解密结果: %s", plaintext, decrypted)
|
||||
ciphertext, err := aesx.EncryptCBC(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("用 GenerateKey 生成的密钥加密失败: %v", err)
|
||||
}
|
||||
decrypted, err := aesx.DecryptCBC(ciphertext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("解密失败: %v", err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Errorf("往返不一致: 得到 %q, 期望 %q", decrypted, plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCFB(t *testing.T) {
|
||||
key := "example key 1234"
|
||||
plaintext := "exampleplaintext"
|
||||
func TestAllModesRoundTrip(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
|
||||
// 测试CFB加密和解密
|
||||
encrypted, err := aesx.EncryptCFBHex(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CFB加密失败: %v", err)
|
||||
encryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": aesx.EncryptECB, "CBC": aesx.EncryptCBC, "CFB": aesx.EncryptCFB,
|
||||
"OFB": aesx.EncryptOFB, "CTR": aesx.EncryptCTR,
|
||||
}
|
||||
fmt.Printf("CFB加密结果: %s\n", encrypted)
|
||||
|
||||
decrypted, err := aesx.DecryptCFBHex(encrypted, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CFB解密失败: %v", err)
|
||||
decryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": aesx.DecryptECB, "CBC": aesx.DecryptCBC, "CFB": aesx.DecryptCFB,
|
||||
"OFB": aesx.DecryptOFB, "CTR": aesx.DecryptCTR,
|
||||
}
|
||||
fmt.Printf("CFB解密结果: %s\n", decrypted)
|
||||
|
||||
if decrypted != plaintext {
|
||||
t.Fatalf("CFB解密结果不匹配,原文: %s, 解密结果: %s", plaintext, decrypted)
|
||||
plaintexts := [][]byte{
|
||||
{}, []byte("a"), []byte("0123456789abcde"), []byte("0123456789abcdef"),
|
||||
[]byte("0123456789abcdefg"), bytes.Repeat([]byte("AES"), 500),
|
||||
}
|
||||
|
||||
for name, encrypt := range encryptors {
|
||||
for i, plaintext := range plaintexts {
|
||||
ciphertext, err := encrypt(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s 明文#%d 加密失败: %v", name, i, err)
|
||||
}
|
||||
decrypted, err := decryptors[name](ciphertext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s 明文#%d 解密失败: %v", name, i, err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Errorf("%s 明文#%d 往返不一致", name, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOFB(t *testing.T) {
|
||||
key := "example key 1234"
|
||||
plaintext := "exampleplaintext"
|
||||
func TestHexAPIRoundTrip(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize128)
|
||||
plaintext := []byte("十六进制 API 往返测试")
|
||||
|
||||
// 测试OFB加密和解密
|
||||
encrypted, err := aesx.EncryptOFBHex(plaintext, key)
|
||||
cases := []struct {
|
||||
name string
|
||||
encrypt func([]byte, []byte) (string, error)
|
||||
decrypt func(string, []byte) ([]byte, error)
|
||||
}{
|
||||
{"ECB", aesx.EncryptECBHex, aesx.DecryptECBHex},
|
||||
{"CBC", aesx.EncryptCBCHex, aesx.DecryptCBCHex},
|
||||
{"CFB", aesx.EncryptCFBHex, aesx.DecryptCFBHex},
|
||||
{"OFB", aesx.EncryptOFBHex, aesx.DecryptOFBHex},
|
||||
{"CTR", aesx.EncryptCTRHex, aesx.DecryptCTRHex},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
hexStr, err := c.encrypt(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s Hex 加密失败: %v", c.name, err)
|
||||
}
|
||||
// 输出必须是大写十六进制,且不含换行符(旧实现会带上 \n)
|
||||
if bytes.ContainsAny([]byte(hexStr), "\n\r \t") {
|
||||
t.Errorf("%s Hex 输出含空白字符: %q", c.name, hexStr)
|
||||
}
|
||||
for _, r := range hexStr {
|
||||
if (r < '0' || r > '9') && (r < 'A' || r > 'F') {
|
||||
t.Fatalf("%s Hex 输出含非大写十六进制字符: %q", c.name, hexStr)
|
||||
}
|
||||
}
|
||||
|
||||
decrypted, err := c.decrypt(hexStr, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s Hex 解密失败: %v", c.name, err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Errorf("%s Hex 往返不一致", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithIVRoundTrip(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
iv := bytes.Repeat([]byte{0x5A}, aesx.BlockSize)
|
||||
plaintext := []byte("fixed iv interop")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
encrypt func([]byte, []byte, []byte) ([]byte, error)
|
||||
decrypt func([]byte, []byte, []byte) ([]byte, error)
|
||||
}{
|
||||
{"CBC", aesx.EncryptCBCWithIV, aesx.DecryptCBCWithIV},
|
||||
{"CFB", aesx.EncryptCFBWithIV, aesx.DecryptCFBWithIV},
|
||||
{"OFB", aesx.EncryptOFBWithIV, aesx.DecryptOFBWithIV},
|
||||
{"CTR", aesx.EncryptCTRWithIV, aesx.DecryptCTRWithIV},
|
||||
}
|
||||
for _, c := range cases {
|
||||
ciphertext, err := c.encrypt(plaintext, key, iv)
|
||||
if err != nil {
|
||||
t.Fatalf("%s WithIV 加密失败: %v", c.name, err)
|
||||
}
|
||||
decrypted, err := c.decrypt(ciphertext, key, iv)
|
||||
if err != nil {
|
||||
t.Fatalf("%s WithIV 解密失败: %v", c.name, err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Errorf("%s WithIV 往返不一致", c.name)
|
||||
}
|
||||
// 错误 IV 下,CBC 通常会因填充校验失败报错,流式模式则会静默返回垃圾
|
||||
// 明文(这正是这些模式不提供完整性保护的体现)。无论哪种情况,都绝不
|
||||
// 允许还原出正确明文。
|
||||
wrongIV, err := c.decrypt(ciphertext, key, bytes.Repeat([]byte{0x00}, aesx.BlockSize))
|
||||
if err == nil && bytes.Equal(wrongIV, plaintext) {
|
||||
t.Errorf("%s 使用错误 IV 却解出了正确明文", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestECBIsDeterministic 记录 ECB 的固有弱点(相同明文块 → 相同密文块),
|
||||
// 与 CBC 对比以证明文档中的安全警告属实。
|
||||
func TestECBIsDeterministic(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
plaintext := bytes.Repeat([]byte("0123456789abcdef"), 4)
|
||||
|
||||
ecb1, err := aesx.EncryptECB(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("OFB加密失败: %v", err)
|
||||
t.Fatalf("ECB 加密失败: %v", err)
|
||||
}
|
||||
fmt.Printf("OFB加密结果: %s\n", encrypted)
|
||||
|
||||
decrypted, err := aesx.DecryptOFBHex(encrypted, key)
|
||||
ecb2, err := aesx.EncryptECB(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("OFB解密失败: %v", err)
|
||||
t.Fatalf("ECB 加密失败: %v", err)
|
||||
}
|
||||
if !bytes.Equal(ecb1, ecb2) {
|
||||
t.Error("ECB 应当是确定性的(这正是它的弱点)")
|
||||
}
|
||||
fmt.Printf("OFB解密结果: %s\n", decrypted)
|
||||
|
||||
if decrypted != plaintext {
|
||||
t.Fatalf("OFB解密结果不匹配,原文: %s, 解密结果: %s", plaintext, decrypted)
|
||||
cbc1, err := aesx.EncryptCBC(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CBC 加密失败: %v", err)
|
||||
}
|
||||
}
|
||||
cbc2, err := aesx.EncryptCBC(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CBC 加密失败: %v", err)
|
||||
}
|
||||
if bytes.Equal(cbc1, cbc2) {
|
||||
t.Error("CBC 使用了随机 IV,两次加密结果不应相同")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedCiphertextNeverPanics(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
decryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": aesx.DecryptECB, "CBC": aesx.DecryptCBC, "CFB": aesx.DecryptCFB,
|
||||
"OFB": aesx.DecryptOFB, "CTR": aesx.DecryptCTR,
|
||||
}
|
||||
for _, decrypt := range decryptors {
|
||||
for n := 0; n <= 40; n++ {
|
||||
// 不应 panic
|
||||
_, _ = decrypt(bytes.Repeat([]byte{0x7F}, n), key)
|
||||
}
|
||||
}
|
||||
|
||||
// ECB / CBC 的非对齐密文必须返回 ErrNotBlockAligned
|
||||
nonAligned := bytes.Repeat([]byte{0xAB}, 20)
|
||||
if _, err := aesx.DecryptECB(nonAligned, key); !errors.Is(err, cipherx.ErrNotBlockAligned) {
|
||||
t.Errorf("ECB 非对齐: 期望 ErrNotBlockAligned, 得到 %v", err)
|
||||
}
|
||||
if _, err := aesx.DecryptCBC(nonAligned, key); !errors.Is(err, cipherx.ErrNotBlockAligned) {
|
||||
t.Errorf("CBC 非对齐: 期望 ErrNotBlockAligned, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- GCM ----
|
||||
|
||||
func TestGCMRoundTrip(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
plaintexts := [][]byte{
|
||||
{}, []byte("a"), []byte("GCM 往返测试"), bytes.Repeat([]byte("x"), 100000),
|
||||
}
|
||||
for i, plaintext := range plaintexts {
|
||||
ciphertext, nonce, err := aesx.EncryptGCM(plaintext, key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 加密#%d 失败: %v", i, err)
|
||||
}
|
||||
if len(nonce) != aesx.GCMNonceSize {
|
||||
t.Fatalf("nonce 长度 = %d, 期望 %d", len(nonce), aesx.GCMNonceSize)
|
||||
}
|
||||
// 密文应等于明文长度 + 认证标签
|
||||
if len(ciphertext) != len(plaintext)+aesx.GCMTagSize {
|
||||
t.Errorf("密文长度 = %d, 期望 %d", len(ciphertext), len(plaintext)+aesx.GCMTagSize)
|
||||
}
|
||||
|
||||
decrypted, err := aesx.DecryptGCM(ciphertext, key, nonce, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 解密#%d 失败: %v", i, err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Errorf("GCM 往返#%d 不一致", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCMNonceIsRandom(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
seen := make(map[string]bool)
|
||||
for i := 0; i < 64; i++ {
|
||||
_, nonce, err := aesx.EncryptGCM([]byte("same"), key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 加密失败: %v", err)
|
||||
}
|
||||
if seen[string(nonce)] {
|
||||
t.Fatal("GCM nonce 重复,会导致灾难性的密钥恢复攻击")
|
||||
}
|
||||
seen[string(nonce)] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCMBindsAAD(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
plaintext := []byte("authenticated data test")
|
||||
aad := []byte("v1|user=42")
|
||||
|
||||
ciphertext, nonce, err := aesx.EncryptGCM(plaintext, key, aad)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 加密失败: %v", err)
|
||||
}
|
||||
|
||||
// 正确的 AAD 可解密
|
||||
if _, err := aesx.DecryptGCM(ciphertext, key, nonce, aad); err != nil {
|
||||
t.Fatalf("正确 AAD 解密失败: %v", err)
|
||||
}
|
||||
// 不同的 AAD 必须失败
|
||||
if _, err := aesx.DecryptGCM(ciphertext, key, nonce, []byte("v1|user=43")); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("错误 AAD: 期望 ErrAuthenticationFailed, 得到 %v", err)
|
||||
}
|
||||
// 缺少 AAD 必须失败
|
||||
if _, err := aesx.DecryptGCM(ciphertext, key, nonce, nil); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("缺失 AAD: 期望 ErrAuthenticationFailed, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGCMTamperDetection 验证任何一处篡改都会导致解密失败,且不返回明文。
|
||||
func TestGCMTamperDetection(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
plaintext := []byte("tamper detection")
|
||||
ciphertext, nonce, err := aesx.EncryptGCM(plaintext, key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 加密失败: %v", err)
|
||||
}
|
||||
|
||||
// 翻转密文(含标签)中每一个字节
|
||||
for i := range ciphertext {
|
||||
tampered := bytes.Clone(ciphertext)
|
||||
tampered[i] ^= 0x01
|
||||
got, err := aesx.DecryptGCM(tampered, key, nonce, nil)
|
||||
if !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("篡改密文第 %d 字节: 期望认证失败, 得到 %v", i, err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Errorf("篡改密文第 %d 字节: 认证失败却返回了明文 %q", i, got)
|
||||
}
|
||||
}
|
||||
|
||||
// 翻转 nonce 中每一个字节
|
||||
for i := range nonce {
|
||||
tampered := bytes.Clone(nonce)
|
||||
tampered[i] ^= 0x01
|
||||
if _, err := aesx.DecryptGCM(ciphertext, key, tampered, nil); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("篡改 nonce 第 %d 字节: 期望认证失败, 得到 %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 错误密钥
|
||||
wrongKey := testKey(t, aesx.KeySize256)
|
||||
if _, err := aesx.DecryptGCM(ciphertext, wrongKey, nonce, nil); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("错误密钥: 期望认证失败, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCMInvalidInputs(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
ciphertext, nonce, err := aesx.EncryptGCM([]byte("data"), key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GCM 加密失败: %v", err)
|
||||
}
|
||||
|
||||
// nonce 长度错误
|
||||
for _, badNonce := range [][]byte{nil, {}, bytes.Repeat([]byte{1}, 8), bytes.Repeat([]byte{1}, 16)} {
|
||||
if _, err := aesx.DecryptGCM(ciphertext, key, badNonce, nil); !errors.Is(err, aesx.ErrInvalidNonceSize) {
|
||||
t.Errorf("nonce 长度 %d: 期望 ErrInvalidNonceSize, 得到 %v", len(badNonce), err)
|
||||
}
|
||||
}
|
||||
|
||||
// 密文短于认证标签
|
||||
if _, err := aesx.DecryptGCM(bytes.Repeat([]byte{1}, aesx.GCMTagSize-1), key, nonce, nil); !errors.Is(err, aesx.ErrCiphertextTooShort) {
|
||||
t.Errorf("超短密文: 期望 ErrCiphertextTooShort, 得到 %v", err)
|
||||
}
|
||||
// 空密文
|
||||
if _, err := aesx.DecryptGCM(nil, key, nonce, nil); !errors.Is(err, aesx.ErrCiphertextTooShort) {
|
||||
t.Errorf("空密文: 期望 ErrCiphertextTooShort, 得到 %v", err)
|
||||
}
|
||||
// 密钥长度错误
|
||||
if _, err := aesx.DecryptGCM(ciphertext, []byte("short"), nonce, nil); !errors.Is(err, cipherx.ErrInvalidKeySize) {
|
||||
t.Errorf("错误密钥长度: 期望 ErrInvalidKeySize, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSealOpenGCM(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize128)
|
||||
plaintext := []byte("single field storage")
|
||||
aad := []byte("ctx")
|
||||
|
||||
sealed, err := aesx.SealGCM(plaintext, key, aad)
|
||||
if err != nil {
|
||||
t.Fatalf("SealGCM 失败: %v", err)
|
||||
}
|
||||
if len(sealed) != aesx.GCMNonceSize+len(plaintext)+aesx.GCMTagSize {
|
||||
t.Errorf("SealGCM 长度 = %d, 期望 %d", len(sealed), aesx.GCMNonceSize+len(plaintext)+aesx.GCMTagSize)
|
||||
}
|
||||
|
||||
opened, err := aesx.OpenGCM(sealed, key, aad)
|
||||
if err != nil {
|
||||
t.Fatalf("OpenGCM 失败: %v", err)
|
||||
}
|
||||
if !bytes.Equal(opened, plaintext) {
|
||||
t.Errorf("Seal/Open 往返不一致")
|
||||
}
|
||||
|
||||
// AAD 不匹配
|
||||
if _, err := aesx.OpenGCM(sealed, key, []byte("other")); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("错误 AAD: 期望认证失败, 得到 %v", err)
|
||||
}
|
||||
// 数据过短
|
||||
for n := 0; n < aesx.GCMNonceSize+aesx.GCMTagSize; n++ {
|
||||
if _, err := aesx.OpenGCM(bytes.Repeat([]byte{0x01}, n), key, aad); err == nil {
|
||||
t.Errorf("长度 %d 的数据: 期望错误, 得到 nil", n)
|
||||
}
|
||||
}
|
||||
// 篡改
|
||||
tampered := bytes.Clone(sealed)
|
||||
tampered[len(tampered)-1] ^= 0x01
|
||||
if _, err := aesx.OpenGCM(tampered, key, aad); !errors.Is(err, aesx.ErrAuthenticationFailed) {
|
||||
t.Errorf("篡改数据: 期望认证失败, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCMHexRoundTrip(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
plaintext := []byte("hex gcm")
|
||||
|
||||
ciphertextHex, nonceHex, err := aesx.EncryptGCMHex(plaintext, key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EncryptGCMHex 失败: %v", err)
|
||||
}
|
||||
decrypted, err := aesx.DecryptGCMHex(ciphertextHex, nonceHex, key, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DecryptGCMHex 失败: %v", err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Error("GCM Hex 往返不一致")
|
||||
}
|
||||
|
||||
if _, err := aesx.DecryptGCMHex("not hex", nonceHex, key, nil); err == nil {
|
||||
t.Error("非法密文十六进制: 期望错误")
|
||||
}
|
||||
if _, err := aesx.DecryptGCMHex(ciphertextHex, "not hex", key, nil); err == nil {
|
||||
t.Error("非法 nonce 十六进制: 期望错误")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCMWithNonceInterop(t *testing.T) {
|
||||
key := testKey(t, aesx.KeySize256)
|
||||
nonce := bytes.Repeat([]byte{0x42}, aesx.GCMNonceSize)
|
||||
plaintext := []byte("interop")
|
||||
|
||||
ciphertext, err := aesx.EncryptGCMWithNonce(plaintext, key, nonce, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EncryptGCMWithNonce 失败: %v", err)
|
||||
}
|
||||
decrypted, err := aesx.DecryptGCM(ciphertext, key, nonce, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("解密失败: %v", err)
|
||||
}
|
||||
if !bytes.Equal(decrypted, plaintext) {
|
||||
t.Error("往返不一致")
|
||||
}
|
||||
|
||||
if _, err := aesx.EncryptGCMWithNonce(plaintext, key, []byte("bad"), nil); !errors.Is(err, aesx.ErrInvalidNonceSize) {
|
||||
t.Errorf("非法 nonce 长度: 期望 ErrInvalidNonceSize, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user