func Sm4Encryption(key, iv, plainText []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData := PKCS5Padding(plainText, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
cryted := make([]byte, len(origData))
blockMode.CryptBlocks(cryted, origData)
return cryted, nil
}
func Sm4Decryption(key, iv, cipherText []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(cipherText))
blockMode.CryptBlocks(origData, cipherText)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
func main() {
originalText := "sysys"
fmt.Println(originalText)
mytext := []byte(originalText)
key := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
iv := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
cryptoText, _ := Sm4Encryption(key, iv, mytext)
fmt.Println(string(cryptoText))
decryptedText, _ := Sm4Decryption(key, iv, cryptoText)
fmt.Println(string(decryptedText))
}
the result of this way is different from openssl enc sm4-cbc,why?
test:
openssl:rom@rom-cd:/cer/sm4$ openssl enc -sm4-cbc -K 1d5c66c44102c7b87a466c30313be4ee -iv 1d5c66c44102c7b87a466c30313be4ee -p -v -nosalt -base64 -in src-test -out dst.sm4
bufsize=8192
key=1D5C66C44102C7B87A466C30313BE4EE
iv =1D5C66C44102C7B87A466C30313BE4EE
bytes read : 95
bytes written: 130
rom@rom-cd:/cer/sm4$ cat dst.sm4
aSAhgpGpRIxQemxbZJ/4e/nRDm/JIpxldx25ZXWU8VgfStRDaV2dH/ngNlDRfknk
EhXIXLM2AU88F/ww8+Z5YhjRZjQjPNjZyrkJ/ZH2nJg3x83J0GZwMxq1d492JQfb
//加密内容经过base64
gmsm:
TestSM4Encrypt hex keybts string ct base64 aSAhgpGpRIxQemxbZJ/4e/nRDm/JIpxldx25ZXWU8VgfStRDaV2dH/ngNlDRfknkEhXIXLM2AU88F/ww8+Z5YhjRZjQjPNjZyrkJ/ZH2nJiNUAPDMH1UZSQ572PUOJno
加密key:
key := []byte{29, 92, 102, 196, 65, 2, 199, 184, 122, 70, 108, 48, 49, 59, 228, 238}
// 128比特iv
iv := []byte{29, 92, 102, 196, 65, 2, 199, 184, 122, 70, 108, 48, 49, 59, 228, 238}
内容 data := []byte("Hello World itoy irajfja;fa; jfapjfpajfpbsgblsgslghsg;sjg;sjg;sjg;js;yofgfgajfjafgjhagjfgakfgk")
加密结果比较:两者最后22位不相同,无法用openssl解密gmsm加密内容