package crypter
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
|
|
"crypto/des"
|
|
"encoding/hex"
|
|
)
|
|
|
|
// ECB模式加密,返回16进制结果
|
|
func TripleECBEncryptForHex(key, plaintext string) (string, error) {
|
|
|
|
keyBytes, err := base64.StdEncoding.DecodeString(key)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
data := []byte(plaintext)
|
|
ciphertext, err := TripleECBEncrypt(keyBytes, data)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(ciphertext), nil
|
|
}
|
|
|
|
// ECB模式解密16进制密文
|
|
func TripleECBDecryptFromHex(key, plaintext string) (string, error) {
|
|
|
|
keyBytes, err := base64.StdEncoding.DecodeString(key)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
data, err := hex.DecodeString(plaintext)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
ciphertext, err := TripleECBDecrypt(keyBytes, data)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(ciphertext), nil
|
|
}
|
|
|
|
// ECB模式加密,返回byte
|
|
func TripleECBEncrypt(key, plaintext []byte) ([]byte, error) {
|
|
|
|
// 创建Triple DES的块加密器
|
|
block, err := des.NewTripleDESCipher(key)
|
|
if err != nil {
|
|
return []byte(""), err
|
|
}
|
|
|
|
// 创建切片来存储加密后的密文
|
|
ciphertext := make([]byte, len(plaintext))
|
|
|
|
// 复制明文到切片中
|
|
copy(ciphertext, plaintext)
|
|
|
|
// 应用PKCS#7填充
|
|
ciphertext = PKCS5Padding(ciphertext, block.BlockSize())
|
|
|
|
// 使用ECB模式加密填充后的数据
|
|
for i := 0; i < len(ciphertext); i += block.BlockSize() {
|
|
block.Encrypt(ciphertext[i:i+block.BlockSize()], ciphertext[i:i+block.BlockSize()])
|
|
}
|
|
|
|
return ciphertext, nil
|
|
|
|
}
|
|
|
|
// ECB模式解密,返回byte
|
|
func TripleECBDecrypt(key, ciphertext []byte) ([]byte, error) {
|
|
// 创建Triple DES的块加密器(解密时也需要这个)
|
|
block, err := des.NewTripleDESCipher(key)
|
|
if err != nil {
|
|
return []byte(""), err
|
|
}
|
|
|
|
// 检查密文长度是否是8字节的倍数
|
|
if len(ciphertext)%des.BlockSize != 0 {
|
|
return []byte(""), errors.New("ciphertext is not a multiple of the block size")
|
|
}
|
|
|
|
// 创建一个buffer来存储解密后的明文
|
|
plaintext := make([]byte, len(ciphertext))
|
|
|
|
// 使用ECB模式解密
|
|
for i := 0; i < len(ciphertext); i += block.BlockSize() {
|
|
block.Decrypt(plaintext[i:i+block.BlockSize()], ciphertext[i:i+block.BlockSize()])
|
|
}
|
|
plaintext = PKCS5UnPadding(plaintext)
|
|
|
|
// 打印解密后的明文
|
|
|
|
return plaintext, nil
|
|
}
|