package sm2cryptography
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"github.com/tjfoc/gmsm/sm2"
"github.com/tjfoc/gmsm/x509"
)
// SM2EncodeBase64 sm2公钥加密,密文base64编码
func SM2EncodeBase64(pubKey string, plaintext string) (string, error) {
pub, err := x509.ReadPublicKeyFromHex(pubKey)
if err != nil {
return "", err
}
cipher, err := sm2.Encrypt(pub, []byte(plaintext), rand.Reader, 0)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(cipher), nil
}
// SM2DecodeBase64 sm2私钥解密,密文base64编码
func SM2DecodeBase64(privKey string, data string) (string, error) {
priv, err := x509.ReadPrivateKeyFromHex(privKey)
if err != nil {
return "", err
}
ciphertext, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return "", err
}
plaintext, err := sm2.Decrypt(priv, []byte(ciphertext), 0)
if err != nil {
return "", err
}
return string(plaintext), nil
}
// SM2Encode sm2公钥加密
func SM2Encode(pubKey string, plaintext string) (string, error) {
pubMen, err := x509.ReadPublicKeyFromHex(pubKey)
if err != nil {
return "", err
}
msg := []byte(plaintext)
ciphertxt, err := sm2.Encrypt(pubMen, msg, rand.Reader, 0)
if err != nil {
return "", err
}
return hex.EncodeToString(ciphertxt), nil
}
// SM2Decode sm2私钥解密
func SM2Decode(privKey string, data string) (string, error) {
priv, err := x509.ReadPrivateKeyFromHex(privKey)
if err != nil {
return "", err
}
ciphertext, err := hex.DecodeString(data)
if err != nil {
return "", err
}
plaintext, err := sm2.Decrypt(priv, []byte(ciphertext), 0)
if err != nil {
return "", err
}
return string(plaintext), nil
}
golang sm2加解密
于 2023-08-01 14:25:08 首次发布