sm4 ecb zeropadding解密乱码
zhangwei911 opened this issue · 0 comments
zhangwei911 commented
密文使用java生成的(Hutool)
func zeroPadding(src []byte) []byte {
padding := 0
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func zeroUnPadding(src []byte) ([]byte, error) {
length := len(src)
count := 0
for i := 0; i < length; i++ {
if src[len(src)-(i+1)] == 0 {
//src = src[:(len(src) - 1)]
count++
} else {
break
}
}
return src[:(length - count)], nil
}
func Sm4Ecb(key []byte, in []byte, mode bool) (out []byte, err error) {
if len(key) != sm4.BlockSize {
return nil, errors.New("SM4: invalid key size " + strconv.Itoa(len(key)))
}
var inData []byte
if mode {
inData = zeroPadding(in)
} else {
inData = in
}
out = make([]byte, len(inData))
c, err := sm4.NewCipher(key)
if err != nil {
panic(err)
}
if mode {
for i := 0; i < len(inData)/16; i++ {
in_tmp := inData[i*16 : i*16+16]
out_tmp := make([]byte, 16)
c.Encrypt(out_tmp, in_tmp)
copy(out[i*16:i*16+16], out_tmp)
}
} else {
for i := 0; i < len(inData)/16; i++ {
in_tmp := inData[i*16 : i*16+16]
out_tmp := make([]byte, 16)
c.Decrypt(out_tmp, in_tmp)
copy(out[i*16:i*16+16], out_tmp)
}
out, _ = zeroUnPadding(out)
}
return out, nil
}