完善不同加密方法的使用

This commit is contained in:
yun
2026-09-30 15:49:12 +08:00
parent 034315ddbd
commit 7db722f8b9
69 changed files with 21362 additions and 2563 deletions
+184 -173
View File
@@ -1,203 +1,214 @@
// Package desx 提供 DES 分组密码的加解密封装,支持 ECB/CBC/CFB/OFB/CTR。
//
// # 安全警告
//
// DES 的有效密钥长度只有 56 位,早已可被专用硬件在数小时内暴力破解,
// **不应用于保护任何机密数据**。本包仅为兼容无法改动的既有系统(老银行接口、
// 老式终端、遗留数据库字段)而保留,新系统请使用 AES-GCM 或
// ChaCha20-Poly1305。
//
// 此外,本包所有模式都**不提供完整性保护**:攻击者可以篡改密文而不被发现
// (CFB/OFB/CTR 甚至可以直接翻转明文的任意比特)。若必须使用 DES,请额外
// 配合 HMAC 做「先加密后认证」。
package desx
import (
"bytes"
"crypto/cipher"
"crypto/des"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
"code.yun.ink/pkg/encryptx/cipherx"
)
// DES-ECB 加密,返回大写的十六进制字符串
func EncryptECBHex(input, key string) (string, error) {
// 创建DES加密器
block, err := des.NewCipher([]byte(key))
const (
// KeySize 是 DES 的密钥长度(字节)。56 位有效强度,已不安全。
KeySize = 8
// BlockSize 是 DES 的分组长度(字节)。
BlockSize = des.BlockSize
)
// Suite 绑定 DES 的分组构造方式与合法密钥长度,模式实现由 cipherx 提供。
//
// 导出它是为了让调用方能够以统一方式驱动任意模式,而无需在本包与 cipherx
// 之间写 switch。
var Suite = cipherx.NewSuite("DES", des.NewCipher, BlockSize, KeySize)
// GenerateKey 用 crypto/rand 生成 8 字节 DES 密钥。
//
// 注意:DES 密钥中的每第 8 位是奇偶校验位,不参与加密,因此实际强度只有
// 56 位。该函数生成的密钥未做校验位设置,可直接使用。
func GenerateKey() ([]byte, error) {
key := make([]byte, KeySize)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return nil, fmt.Errorf("desx: 生成密钥失败: %w", err)
}
return key, nil
}
// GenerateKeyHex 生成 DES 密钥并以十六进制字符串返回。
//
// 注意:返回值是**编码后的文本**,不能直接当密钥使用。读回后必须先解码
// (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
}
// DES-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.NewCipher([]byte(key))
if err != nil {
return "", fmt.Errorf("创建DES解密器失败: %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 使用 DES-ECB 加密并做 PKCS#7 填充。
func EncryptECB(plaintext, key []byte) ([]byte, error) {
return Suite.Encrypt(cipherx.ECB, plaintext, key)
}
// DES-CBC 加密
func EncryptCBCHex(plaintext, key string) (string, error) {
block, err := des.NewCipher([]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 解密 DES-ECB 密文。
func DecryptECB(ciphertext, key []byte) ([]byte, error) {
return Suite.Decrypt(cipherx.ECB, ciphertext, key)
}
// DES-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.NewCipher([]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)
}
// DES-CFB 加密
func EncryptCFBHex(plaintext, key string) (string, error) {
block, err := des.NewCipher([]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 解密十六进制 DES-ECB 密文,大小写均可。
func DecryptECBHex(ciphertextHex string, key []byte) ([]byte, error) {
return Suite.DecryptHex(cipherx.ECB, ciphertextHex, key)
}
// DES-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.NewCipher([]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 使用 DES-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 解密 DES-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 解密十六进制 DES-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 使用 DES-CFB 加密,随机 IV 前置在密文之前。
func EncryptCFB(plaintext, key []byte) ([]byte, error) {
return Suite.Encrypt(cipherx.CFB, plaintext, key)
}
// DecryptCFB 解密 DES-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 解密十六进制 DES-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 使用 DES-OFB 加密,随机 IV 前置在密文之前。
func EncryptOFB(plaintext, key []byte) ([]byte, error) {
return Suite.Encrypt(cipherx.OFB, plaintext, key)
}
// DecryptOFB 解密 DES-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 解密十六进制 DES-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 使用 DES-CTR 加密,随机 IV 前置在密文之前。
func EncryptCTR(plaintext, key []byte) ([]byte, error) {
return Suite.Encrypt(cipherx.CTR, plaintext, key)
}
// DecryptCTR 解密 DES-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 解密十六进制 DES-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)
}