golang 对接 java 版的国密算法(Sm2SignWithSm3)

第三方加密算法升级国密SM2,找了好久才解决,直接上代码

需要依赖大神的包

https://github.com/ZZMarquis/gm

直接上源码

package sm2

import (
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"github.com/ZZMarquis/gm/sm2"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"io/ioutil"
	"os"
)

type strings struct {
	Strings string `json:"strings"`
}

func getPrivateKey(path string) string {
	str, _ := os.Getwd()
	separator := string(os.PathSeparator)
	f, err := ioutil.ReadFile(str + separator + "static" + separator + path + separator + "sm2PrivateKey.txt")
	if err != nil {
		logrus.Println("getPrivateKey error: ", err)
	}
	return cast.ToString(f)
}

func GetSign(ctx *gin.Context) {
	data, _ := ioutil.ReadAll(ctx.Request.Body)
	var tempStrings strings
	err := json.Unmarshal(data, &tempStrings)
	if err != nil {
		logrus.Println("GetSign get tempString err: ", err)
	}
	// 获取私钥
	privateKey := getPrivateKey(utils.Cfg.KeyPath)
	// 解码hex私钥
	privateKeyByte, err := hex.DecodeString(privateKey)
	if err != nil {
		logrus.Println("DecodeString privateKey error: ", err)
	}
	// 转成go版的私钥
	pri, err := sm2.RawBytesToPrivateKey(privateKeyByte)
	if err != nil {
		logrus.Println("RawBytesToPrivateKey error: ", err)
	}
	// 携带uid 的sign
	signature, err := sm2.Sign(pri, []byte("1234567812345678"), []byte(tempStrings.Strings))
	if err != nil {
		logrus.Println("Sign error: ", err)
	}
	// 转 base64
	sign := base64.StdEncoding.EncodeToString(signature)
	logrus.Println("** getSign: ", sign)
	ctx.String(200, sign)
}