国密算法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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值