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

}

相关推荐
疯狂的喵1 天前
C++编译期多态实现
开发语言·c++·算法
2301_765703141 天前
C++中的协程编程
开发语言·c++·算法
m0_748708051 天前
实时数据压缩库
开发语言·c++·算法
lly2024061 天前
jQuery Mobile 表格
开发语言
惊讶的猫1 天前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
m0_748233171 天前
30秒掌握C++核心精髓
开发语言·c++
Fleshy数模1 天前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
Duang007_1 天前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
froginwe111 天前
Redis 管道技术
开发语言
有来技术1 天前
Spring Boot 4 + Vue3 企业级多租户 SaaS:从共享 Schema 架构到商业化套餐设计
java·vue.js·spring boot·后端