国密算法Sm2工具类--golang实现版
package main
import (
“crypto/rand”
"encoding/base64"
"fmt"
"github.com/tjfoc/gmsm/sm2"
"github.com/tjfoc/gmsm/x509"
)
type SM2SignatureService struct{}
func (s *SM2SignatureService) Verify(content, charset, publicKey, sign string) (bool, error) {
data := []byte(content)
pubbytes, err := base64.StdEncoding.DecodeString(publicKey)
pubKey, err := x509.ParseSm2PublicKey(pubbytes)
if err != nil {
return false, fmt.Errorf(“failed to parse public key: %v”, err)
}
// 解码签名
signBytes, err := base64.StdEncoding.DecodeString(sign)
if err != nil {
return false, fmt.Errorf("failed to decode signature: %v", err)
}
// 验证签名
return pubKey.Verify(data, signBytes), nil
}
func (s *SM2SignatureService) AlgorithmName() string {
return “SM2”
}
func (s *SM2SignatureService) GenerateKey() (string, string, error) {
// 生成密钥对
privKey, err := sm2.GenerateKey(rand.Reader)
if err != nil {
return “”, “”, fmt.Errorf(“failed to generate key pair: %v”, err)
}
// 序列化私钥(PKCS#8)
privateKeyBytes, err := x509.MarshalSm2PrivateKey(privKey, nil)
if err != nil {
return "", "", fmt.Errorf("failed to marshal private key: %v", err)
}
privKey, err = x509.ParsePKCS8PrivateKey(privateKeyBytes, nil)
if err != nil {
return "", "", fmt.Errorf("failed to parse private key: %v", err)
}
// 序列化公钥
publicKeyBytes, err := x509.MarshalSm2PublicKey(&privKey.PublicKey)
if err != nil {
return "", "", fmt.Errorf("failed to marshal public key: %v", err)
}
return base64.StdEncoding.EncodeToString(publicKeyBytes),
base64.StdEncoding.EncodeToString(privateKeyBytes), nil
}
func (s *SM2SignatureService) Sign(content, charset, privateKey string) (string, error) {
data := []byte(content)
// 解码私钥
privateKeyBytes, err := base64.StdEncoding.DecodeString(privateKey)
if err != nil {
return "", fmt.Errorf("failed to decode private key: %v", err)
}
privKey, err := x509.ParsePKCS8UnecryptedPrivateKey(privateKeyBytes)
if err != nil {
return "", fmt.Errorf("failed to parse private key: %v", err)
}
// 生成签名
signature, err := privKey.Sign(rand.Reader, data, nil)
if err != nil {
return "", fmt.Errorf("failed to sign data: %v", err)
}
return base64.StdEncoding.EncodeToString(signature), nil
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)