49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package ymtcrypto
|
|
|
|
import (
|
|
"crypto/cipher"
|
|
"encoding/base64"
|
|
"errors"
|
|
sm4 "github.com/tjfoc/gmsm/sm4"
|
|
)
|
|
|
|
func SM4Decrypt(encrypted, encryptKey string) (string, error) {
|
|
if encrypted == "" {
|
|
return "", nil
|
|
}
|
|
d, err := base64.StdEncoding.DecodeString(encryptKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(d) != 16 {
|
|
return "", errors.New("invalid sm4 key length")
|
|
}
|
|
cipherBlock, err := sm4.NewCipher(d)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
blockSize := cipherBlock.BlockSize()
|
|
iv := make([]byte, blockSize)
|
|
for i := 0; i < blockSize; i++ { iv[i] = 0 }
|
|
cipherText, err := base64.StdEncoding.DecodeString(encrypted)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(cipherText)%blockSize != 0 {
|
|
return "", errors.New("invalid sm4 ciphertext size")
|
|
}
|
|
plainText := make([]byte, len(cipherText))
|
|
blockMode := cipher.NewCBCDecrypter(cipherBlock, iv)
|
|
blockMode.CryptBlocks(plainText, cipherText)
|
|
if len(plainText) == 0 {
|
|
return "", nil
|
|
}
|
|
padding := int(plainText[len(plainText)-1])
|
|
if padding <= 0 || padding > len(plainText) {
|
|
return "", errors.New("invalid padding")
|
|
}
|
|
buff := plainText[:len(plainText)-padding]
|
|
return string(buff), nil
|
|
}
|
|
|