国密算法Sm2工具类--golang实现版

发布于:2025-02-28 ⋅ 阅读:(14) ⋅ 点赞:(0)

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

}