完善不同加密方法的使用
This commit is contained in:
+183
-173
@@ -1,203 +1,213 @@
|
||||
// Package tdesx 提供三重 DES(3DES / TDEA)的加解密封装,支持 ECB/CBC/CFB/OFB/CTR。
|
||||
//
|
||||
// # 安全警告
|
||||
//
|
||||
// 3DES 的分组长度仍然只有 64 位,在加密超过约 32 GB 数据时会遭遇 Sweet32
|
||||
// 生日攻击,因此 NIST 已于 2023 年正式弃用 3DES。它比单 DES 强得多,但
|
||||
// **新系统不应再选用**:AES 更快也更安全。本包仅为兼容无法改动的既有系统
|
||||
// (老支付网关、老终端协议)而保留。
|
||||
//
|
||||
// 另外,本包所有模式都**不提供完整性保护**,密文可被篡改而不被发现。若必须
|
||||
// 使用 3DES,请额外配合 HMAC 做「先加密后认证」。
|
||||
package tdesx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/cipher"
|
||||
"crypto/des"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"code.yun.ink/pkg/encryptx/cipherx"
|
||||
)
|
||||
|
||||
// 3DES-ECB 加密,返回大写的十六进制字符串
|
||||
func EncryptECBHex(input, key string) (string, error) {
|
||||
// 创建3DES加密器
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
const (
|
||||
// KeySize 是 3DES 的密钥长度(字节),即 3 个独立的 DES 密钥。
|
||||
KeySize = 24
|
||||
// BlockSize 是 3DES 的分组长度(字节)。与单 DES 相同,仍为 64 位。
|
||||
BlockSize = des.BlockSize
|
||||
)
|
||||
|
||||
// Suite 绑定 3DES 的分组构造方式与合法密钥长度,模式实现由 cipherx 提供。
|
||||
//
|
||||
// 导出它是为了让调用方能够以统一方式驱动任意模式,而无需在本包与 cipherx
|
||||
// 之间写 switch。
|
||||
var Suite = cipherx.NewSuite("3DES", des.NewTripleDESCipher, BlockSize, KeySize)
|
||||
|
||||
// GenerateKey 用 crypto/rand 生成 24 字节 3DES 密钥。
|
||||
//
|
||||
// 注意:若三个 8 字节子密钥中存在相等的情况(尤其是 K1==K2==K3),3DES 会
|
||||
// 退化为单 DES。本函数生成的是三个独立随机子密钥,不会退化。
|
||||
func GenerateKey() ([]byte, error) {
|
||||
key := make([]byte, KeySize)
|
||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
||||
return nil, fmt.Errorf("tdesx: 生成密钥失败: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// GenerateKeyHex 生成 3DES 密钥并以十六进制字符串返回。
|
||||
//
|
||||
// 注意:返回值是**编码后的文本**,不能直接当密钥使用。读回后必须先解码
|
||||
// (encoding/hex 的 DecodeString,或本库的 hexx.Decode),再传给 Encrypt/Decrypt。
|
||||
func GenerateKeyHex() (string, error) {
|
||||
key, err := GenerateKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 对输入数据进行PKCS7填充
|
||||
paddedInput := PKCS7Padding([]byte(input), block.BlockSize())
|
||||
|
||||
// ECB模式加密
|
||||
encrypted := make([]byte, len(paddedInput))
|
||||
for i := 0; i < len(paddedInput); i += des.BlockSize {
|
||||
block.Encrypt(encrypted[i:i+des.BlockSize], paddedInput[i:i+des.BlockSize])
|
||||
}
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(encrypted)
|
||||
return strings.ToUpper(result), nil
|
||||
return hex.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// 3DES-ECB 解密,输入大写的十六进制字符串
|
||||
func DecryptECBHex(encryptedHex, key string) (string, error) {
|
||||
encrypted, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
// ---- ECB ----
|
||||
//
|
||||
// 警告:ECB 不具备语义安全性,相同的明文分组会产生相同的密文分组。
|
||||
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("创建3DES解密器失败: %v", err)
|
||||
}
|
||||
|
||||
// ECB模式解密
|
||||
decrypted := make([]byte, len(encrypted))
|
||||
for i := 0; i < len(encrypted); i += des.BlockSize {
|
||||
block.Decrypt(decrypted[i:i+des.BlockSize], encrypted[i:i+des.BlockSize])
|
||||
}
|
||||
|
||||
// 去除PKCS7填充
|
||||
unpaddedData, err := PKCS7UnPadding(decrypted)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("去除填充失败: %v", err)
|
||||
}
|
||||
return string(unpaddedData), nil
|
||||
// EncryptECB 使用 3DES-ECB 加密并做 PKCS#7 填充。
|
||||
func EncryptECB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.ECB, plaintext, key)
|
||||
}
|
||||
|
||||
// 3DES-CBC 加密
|
||||
func EncryptCBCHex(plaintext, key string) (string, error) {
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
blockSize := block.BlockSize()
|
||||
plainBytes := PKCS7Padding([]byte(plaintext), blockSize)
|
||||
|
||||
// 创建密文字节切片,包含IV空间
|
||||
cipherbyte := make([]byte, des.BlockSize+len(plainBytes))
|
||||
|
||||
// 生成随机IV
|
||||
iv := cipherbyte[:des.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建CBC模式加密器
|
||||
blockMode := cipher.NewCBCEncrypter(block, iv)
|
||||
|
||||
// 加密数据
|
||||
blockMode.CryptBlocks(cipherbyte[des.BlockSize:], plainBytes)
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(cipherbyte)
|
||||
return strings.ToUpper(result), nil
|
||||
// DecryptECB 解密 3DES-ECB 密文。
|
||||
func DecryptECB(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.ECB, ciphertext, key)
|
||||
}
|
||||
|
||||
// 3DES-CBC 解密
|
||||
func DecryptCBCHex(encryptedHex, key string) (string, error) {
|
||||
cipherbyte, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
|
||||
if len(cipherbyte) < des.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
iv := cipherbyte[:des.BlockSize]
|
||||
cipherbyte = cipherbyte[des.BlockSize:]
|
||||
if len(cipherbyte)%des.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
|
||||
// EncryptECBHex 与 EncryptECB 相同,返回大写十六进制字符串。
|
||||
func EncryptECBHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.ECB, plaintext, key)
|
||||
}
|
||||
|
||||
// 3DES-CFB 加密
|
||||
func EncryptCFBHex(plaintext, key string) (string, error) {
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建密文字节切片,包含IV空间
|
||||
cipherbyte := make([]byte, des.BlockSize+len(plaintext))
|
||||
|
||||
// 生成随机IV
|
||||
iv := cipherbyte[:des.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建CFB模式加密器
|
||||
stream := cipher.NewCFBEncrypter(block, iv)
|
||||
stream.XORKeyStream(cipherbyte[des.BlockSize:], []byte(plaintext))
|
||||
|
||||
// 转换为十六进制并大写
|
||||
result := hex.EncodeToString(cipherbyte)
|
||||
return strings.ToUpper(result), nil
|
||||
// DecryptECBHex 解密十六进制 3DES-ECB 密文,大小写均可。
|
||||
func DecryptECBHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.ECB, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// 3DES-CFB 解密
|
||||
func DecryptCFBHex(encryptedHex, key string) (string, error) {
|
||||
cipherbyte, err := hex.DecodeString(encryptedHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hex解码失败: %v", err)
|
||||
}
|
||||
// ---- CBC ----
|
||||
|
||||
if len(cipherbyte) < des.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
block, err := des.NewTripleDESCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 获取IV
|
||||
iv := cipherbyte[:des.BlockSize]
|
||||
cipherbyte = cipherbyte[des.BlockSize:]
|
||||
|
||||
// 创建CFB模式解密器
|
||||
stream := cipher.NewCFBDecrypter(block, iv)
|
||||
stream.XORKeyStream(cipherbyte, cipherbyte)
|
||||
|
||||
return string(cipherbyte), nil
|
||||
// EncryptCBC 使用 3DES-CBC 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCBC(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CBC, plaintext, key)
|
||||
}
|
||||
|
||||
// PKCS7补码
|
||||
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
// DecryptCBC 解密 3DES-CBC 密文(IV 前置格式)。
|
||||
func DecryptCBC(ciphertext, key []byte) ([]byte, error) {
|
||||
return Suite.Decrypt(cipherx.CBC, ciphertext, key)
|
||||
}
|
||||
|
||||
// 去除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
|
||||
// EncryptCBCHex 与 EncryptCBC 相同,返回大写十六进制字符串。
|
||||
func EncryptCBCHex(plaintext, key []byte) (string, error) {
|
||||
return Suite.EncryptHex(cipherx.CBC, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCBCHex 解密十六进制 3DES-CBC 密文。
|
||||
func DecryptCBCHex(ciphertextHex string, key []byte) ([]byte, error) {
|
||||
return Suite.DecryptHex(cipherx.CBC, ciphertextHex, key)
|
||||
}
|
||||
|
||||
// EncryptCBCWithIV 使用调用方指定的 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 使用 3DES-CFB 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCFB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCFB 解密 3DES-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 解密十六进制 3DES-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 使用 3DES-OFB 加密,随机 IV 前置在密文之前。
|
||||
func EncryptOFB(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.OFB, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptOFB 解密 3DES-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 解密十六进制 3DES-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 使用 3DES-CTR 加密,随机 IV 前置在密文之前。
|
||||
func EncryptCTR(plaintext, key []byte) ([]byte, error) {
|
||||
return Suite.Encrypt(cipherx.CTR, plaintext, key)
|
||||
}
|
||||
|
||||
// DecryptCTR 解密 3DES-CTR 密文(IV 前置格式)。
|
||||
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 解密十六进制 3DES-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)
|
||||
}
|
||||
|
||||
+150
-63
@@ -1,94 +1,181 @@
|
||||
package tdesx
|
||||
package tdesx_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"code.yun.ink/pkg/encryptx/cipherx"
|
||||
"code.yun.ink/pkg/encryptx/tdesx"
|
||||
)
|
||||
|
||||
func TestEncryptECBHex(t *testing.T) {
|
||||
// 3DES密钥需要24字节
|
||||
key := "123456789012345678901234"
|
||||
input := "hello world"
|
||||
|
||||
encrypted, err := EncryptECBHex(input, key)
|
||||
func TestGenerateKey(t *testing.T) {
|
||||
key, err := tdesx.GenerateKey()
|
||||
if err != nil {
|
||||
t.Errorf("加密失败: %v", err)
|
||||
return
|
||||
t.Fatalf("GenerateKey 失败: %v", err)
|
||||
}
|
||||
if len(key) != tdesx.KeySize {
|
||||
t.Fatalf("密钥长度 = %d, 期望 %d", len(key), tdesx.KeySize)
|
||||
}
|
||||
|
||||
decrypted, err := DecryptECBHex(encrypted, key)
|
||||
if err != nil {
|
||||
t.Errorf("解密失败: %v", err)
|
||||
return
|
||||
other, _ := tdesx.GenerateKey()
|
||||
if bytes.Equal(key, other) {
|
||||
t.Error("两次 GenerateKey 产生了相同密钥")
|
||||
}
|
||||
|
||||
if decrypted != input {
|
||||
t.Errorf("解密结果不匹配,期望: %s, 实际: %s", input, decrypted)
|
||||
hexKey, err := tdesx.GenerateKeyHex()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKeyHex 失败: %v", err)
|
||||
}
|
||||
if len(hexKey) != tdesx.KeySize*2 {
|
||||
t.Errorf("GenerateKeyHex 长度 = %d, 期望 %d", len(hexKey), tdesx.KeySize*2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptCBCHex(t *testing.T) {
|
||||
// 3DES密钥需要24字节
|
||||
key := "123456789012345678901234"
|
||||
input := "hello world"
|
||||
|
||||
encrypted, err := EncryptCBCHex(input, key)
|
||||
if err != nil {
|
||||
t.Errorf("CBC加密失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
decrypted, err := DecryptCBCHex(encrypted, key)
|
||||
if err != nil {
|
||||
t.Errorf("CBC解密失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if decrypted != input {
|
||||
t.Errorf("CBC解密结果不匹配,期望: %s, 实际: %s", input, decrypted)
|
||||
func TestKeySizeValidation(t *testing.T) {
|
||||
plaintext := []byte("hello")
|
||||
for _, wrongLen := range []int{0, 8, 16, 23, 25, 32} {
|
||||
key := bytes.Repeat([]byte{0x01}, wrongLen)
|
||||
if _, err := tdesx.EncryptCBC(plaintext, key); !errors.Is(err, cipherx.ErrInvalidKeySize) {
|
||||
t.Errorf("密钥长度 %d: 期望 ErrInvalidKeySize, 得到 %v", wrongLen, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptCFBHex(t *testing.T) {
|
||||
// 3DES密钥需要24字节
|
||||
key := "123456789012345678901234"
|
||||
input := "hello world"
|
||||
|
||||
encrypted, err := EncryptCFBHex(input, key)
|
||||
func TestAllModesRoundTrip(t *testing.T) {
|
||||
key, err := tdesx.GenerateKey()
|
||||
if err != nil {
|
||||
t.Errorf("CFB加密失败: %v", err)
|
||||
return
|
||||
t.Fatalf("GenerateKey 失败: %v", err)
|
||||
}
|
||||
|
||||
decrypted, err := DecryptCFBHex(encrypted, key)
|
||||
if err != nil {
|
||||
t.Errorf("CFB解密失败: %v", err)
|
||||
return
|
||||
encryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": tdesx.EncryptECB, "CBC": tdesx.EncryptCBC, "CFB": tdesx.EncryptCFB,
|
||||
"OFB": tdesx.EncryptOFB, "CTR": tdesx.EncryptCTR,
|
||||
}
|
||||
decryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": tdesx.DecryptECB, "CBC": tdesx.DecryptCBC, "CFB": tdesx.DecryptCFB,
|
||||
"OFB": tdesx.DecryptOFB, "CTR": tdesx.DecryptCTR,
|
||||
}
|
||||
plaintexts := [][]byte{
|
||||
{}, []byte("a"), []byte("1234567"), []byte("12345678"), []byte("123456789"),
|
||||
bytes.Repeat([]byte("3DES"), 200),
|
||||
}
|
||||
|
||||
if decrypted != input {
|
||||
t.Errorf("CFB解密结果不匹配,期望: %s, 实际: %s", input, decrypted)
|
||||
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 TestPKCS7Padding(t *testing.T) {
|
||||
// 测试PKCS7填充和去除
|
||||
data := []byte("hello")
|
||||
blockSize := 8
|
||||
func TestHexAPIRoundTrip(t *testing.T) {
|
||||
key, _ := tdesx.GenerateKey()
|
||||
plaintext := []byte("十六进制往返")
|
||||
|
||||
// 填充
|
||||
padded := PKCS7Padding(data, blockSize)
|
||||
if len(padded) != blockSize {
|
||||
t.Errorf("填充长度错误,期望: %d, 实际: %d", blockSize, len(padded))
|
||||
cases := []struct {
|
||||
name string
|
||||
encrypt func([]byte, []byte) (string, error)
|
||||
decrypt func(string, []byte) ([]byte, error)
|
||||
}{
|
||||
{"ECB", tdesx.EncryptECBHex, tdesx.DecryptECBHex},
|
||||
{"CBC", tdesx.EncryptCBCHex, tdesx.DecryptCBCHex},
|
||||
{"CFB", tdesx.EncryptCFBHex, tdesx.DecryptCFBHex},
|
||||
{"OFB", tdesx.EncryptOFBHex, tdesx.DecryptOFBHex},
|
||||
{"CTR", tdesx.EncryptCTRHex, tdesx.DecryptCTRHex},
|
||||
}
|
||||
for _, c := range cases {
|
||||
hexStr, err := c.encrypt(plaintext, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s Hex 加密失败: %v", c.name, err)
|
||||
}
|
||||
if bytes.ContainsAny([]byte(hexStr), "\n\r \t") {
|
||||
t.Errorf("%s Hex 输出含空白字符", c.name)
|
||||
}
|
||||
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, _ := tdesx.GenerateKey()
|
||||
iv := bytes.Repeat([]byte{0x5A}, tdesx.BlockSize)
|
||||
plaintext := []byte("fixed iv")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
encrypt func([]byte, []byte, []byte) ([]byte, error)
|
||||
decrypt func([]byte, []byte, []byte) ([]byte, error)
|
||||
}{
|
||||
{"CBC", tdesx.EncryptCBCWithIV, tdesx.DecryptCBCWithIV},
|
||||
{"CFB", tdesx.EncryptCFBWithIV, tdesx.DecryptCFBWithIV},
|
||||
{"OFB", tdesx.EncryptOFBWithIV, tdesx.DecryptOFBWithIV},
|
||||
{"CTR", tdesx.EncryptCTRWithIV, tdesx.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMalformedCiphertextNeverPanics 是 P0-3 在 3DES 上的回归测试。
|
||||
func TestMalformedCiphertextNeverPanics(t *testing.T) {
|
||||
key, _ := tdesx.GenerateKey()
|
||||
decryptors := map[string]func([]byte, []byte) ([]byte, error){
|
||||
"ECB": tdesx.DecryptECB, "CBC": tdesx.DecryptCBC, "CFB": tdesx.DecryptCFB,
|
||||
"OFB": tdesx.DecryptOFB, "CTR": tdesx.DecryptCTR,
|
||||
}
|
||||
for _, decrypt := range decryptors {
|
||||
for n := 0; n <= 24; n++ {
|
||||
_, _ = decrypt(bytes.Repeat([]byte{0x7F}, n), key)
|
||||
}
|
||||
}
|
||||
|
||||
nonAligned := bytes.Repeat([]byte{0xAB}, 12)
|
||||
if _, err := tdesx.DecryptECB(nonAligned, key); !errors.Is(err, cipherx.ErrNotBlockAligned) {
|
||||
t.Errorf("ECB 非对齐: 期望 ErrNotBlockAligned, 得到 %v", err)
|
||||
}
|
||||
if _, err := tdesx.DecryptCBC(nonAligned, key); !errors.Is(err, cipherx.ErrNotBlockAligned) {
|
||||
t.Errorf("CBC 非对齐: 期望 ErrNotBlockAligned, 得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestECBIsDeterministic(t *testing.T) {
|
||||
key, _ := tdesx.GenerateKey()
|
||||
plaintext := bytes.Repeat([]byte("12345678"), 3)
|
||||
|
||||
// 去除填充
|
||||
unpadded, err := PKCS7UnPadding(padded)
|
||||
if err != nil {
|
||||
t.Errorf("去除填充失败: %v", err)
|
||||
return
|
||||
a, _ := tdesx.EncryptECB(plaintext, key)
|
||||
b, _ := tdesx.EncryptECB(plaintext, key)
|
||||
if !bytes.Equal(a, b) {
|
||||
t.Error("ECB 应当是确定性的")
|
||||
}
|
||||
|
||||
if string(unpadded) != string(data) {
|
||||
t.Errorf("去除填充后数据不匹配,期望: %s, 实际: %s", string(data), string(unpadded))
|
||||
c, _ := tdesx.EncryptCBC(plaintext, key)
|
||||
d, _ := tdesx.EncryptCBC(plaintext, key)
|
||||
if bytes.Equal(c, d) {
|
||||
t.Error("CBC 使用了随机 IV,两次结果不应相同")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user