SM2-Golang国密生成方案

发布时间:阅读数:847


直接上代码

package pbchub

import (
	"encoding/hex"
	"math/big"

	"github.com/tjfoc/gmsm/sm2"
)

// GenPublicKey 生成公钥
func GenPublicKey(publicKey string) (*sm2.PublicKey, error) {
	d, err := hex.DecodeString(publicKey)
	if err != nil {
		return nil, err
	}
	c := sm2.P256Sm2()

	return &sm2.PublicKey{Curve: c, X: new(big.Int).SetBytes(d[1:33]), Y: new(big.Int).SetBytes(d[33:])}, nil
}

// GenPrivatekey 生成私钥
func GenPrivatekey(privateKey string, publicKey *sm2.PublicKey) (*sm2.PrivateKey, error) {
	d, err := hex.DecodeString(privateKey)
	if err != nil {
		return nil, err
	}

	return &sm2.PrivateKey{PublicKey: *publicKey, D: new(big.Int).SetBytes(d)}, nil
}