YouChuKoffee/app/utils/Sm4/sm4.go

35 lines
839 B
Go
Raw Normal View History

2024-06-19 18:32:34 +08:00
package Sm4
import (
"crypto/cipher"
sm4 "github.com/tjfoc/gmsm/sm4"
)
func EncryptSM4(plainText string, key string) ([]byte, error) {
block, err := sm4.NewCipher([]byte(key))
if err != nil {
return nil, err
}
ciphertext := make([]byte, len(plainText))
iv := []byte("UISwD9fW6cFh9SNS") // 使用16字节的初始化向量
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, []byte(plainText))
return ciphertext, nil
}
func DecryptSM4(ciphertext string, key string) ([]byte, error) {
block, err := sm4.NewCipher([]byte(key))
if err != nil {
return nil, err
}
plaintext := make([]byte, len(ciphertext))
iv := []byte("UISwD9fW6cFh9SNS") // 使用与加密相同的初始化向量
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plaintext, []byte(ciphertext))
return plaintext, nil
}