Go 语言国密 SM4 加密和解密的实现
依赖库
https://github.com/tjfoc/gmsm
// SM4Encrypt SM4 加密
func SM4Encrypt(origBytes, key []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData := pkcs5Padding(origBytes, blockSize)
iv := make([]byte, sm4.BlockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
encrypted := make([]byte, len(origData))
blockMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
// SM4Decrypt 解密
func SM4Decrypt(encrypted, key []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
iv := make([]byte, sm4.BlockSize)
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(encrypted))
blockMode.CryptBlocks(origData, encrypted)
origData = pkcs5UnPadding(origData)
return origData, nil
}
// pkcs5Padding pkcs5Padding fill
func pkcs5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padText...)
}
// pkcs5UnPadding pkcs5UnPadding
func pkcs5UnPadding(src []byte) []byte {
length := len(src)
if length == 0 {
return nil
}
unPadding := int(src[length-1])
return src[length - unPadding)]
}