1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
cipher_ecb.go 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-08-26 00:18 . sm4 支持
package algorithm
import (
"crypto/cipher"
"errors"
)
// CipherECB 模式加密
type CipherECB struct {
cipherFunc func(key []byte) (cipher.Block, error)
//keySize int
//blockSize int
//identifier asn1.ObjectIdentifier
}
func NewECB(cipherFunc func(key []byte) (cipher.Block, error)) CipherECB {
return CipherECB{cipherFunc: cipherFunc}
}
//// 值大小
//func (ecb CipherECB) KeySize() int {
// return ecb.keySize
//}
//// oid
//func (ecb CipherECB) OID() asn1.ObjectIdentifier {
// return ecb.identifier
//}
// Encrypt 加密
func (ecb CipherECB) Encrypt(plaintext, key []byte, iv []byte) ([]byte, error) {
block, err := ecb.cipherFunc(key)
if err != nil {
return nil, errors.New("pkcs/cipher:" + err.Error() + " failed to create cipher")
}
// 加密数据补码
plaintext = pkcs7Padding(plaintext, block.BlockSize())
// 需要保存的加密数据
encrypted := make([]byte, len(plaintext))
mode := NewECBEncrypt(block)
mode.CryptBlocks(encrypted, plaintext)
return encrypted, nil
}
// Decrypt 解密
func (ecb CipherECB) Decrypt(ciphertext, key []byte, iv []byte) ([]byte, error) {
block, err := ecb.cipherFunc(key)
if err != nil {
return nil, err
}
// 判断数据是否为填充数据
l := len(ciphertext)
if l == 0 || l%block.BlockSize() != 0 {
return nil, errors.New("pkcs/cipher: invalid padding")
}
plaintext := make([]byte, len(ciphertext))
mode := NewECBDecrypter(block)
mode.CryptBlocks(plaintext, ciphertext)
return pkcs7UnPadding(plaintext), nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.0

搜索帮助

344bd9b3 5694891 D2dac590 5694891