ZBLOG

package main import ( "crypto/rand" "fmt" "io/ioutil" "github.com/tjfoc/gmsm/sm2" ) // 生成公钥私钥并写入文件 // privateKeyPath:私钥路径 // publicKeyPath:公钥路径 // password:用于加密私钥 func WriteKeyPairToFile(privateKeyPath, publicKeyPath string, password []byte...

package main

import (

"crypto/rand"
"fmt"
"io/ioutil"

"github.com/tjfoc/gmsm/sm2"

)

// 生成公钥私钥并写入文件 // privateKeyPath:私钥路径 // publicKeyPath:公钥路径 // password:用于加密私钥 func WriteKeyPairToFile(privateKeyPath, publicKeyPath string, password []byte) error {

//生成秘钥对
privateKey, err := sm2.GenerateKey(rand.Reader)
if err != nil {
	return err
}

privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
	return err
}

err = ioutil.WriteFile(privateKeyPath, privateKeyBytes, 0600)
if err != nil {
	return err
}

publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
	return err
}

err = ioutil.WriteFile(publicKeyPath, publicKeyBytes, 0644)
if err != nil {
	return err
}

return nil

}

// 从文件中读取公钥和私钥 func ReadKeyPairFromFile(privateKeyPath, publicKeyPath string) (*sm2.PrivateKey, *sm2.PublicKey, error) {

privateKeyBytes, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
  return nil, nil, fmt.Errorf("failed to read private key file: %w",err)
}

privateKeyBlock,err := pem.Decode(privateKeyBytes)
if privateKeyBlock ==nil || privateKeyBlock.Type !="PRIVATE KEY"{
  return nil,nil,err
}

privateKey,err:=x509.ParsePKCS8PrivateKey(privatekeyBlock.Bytes)
if privateKey==nil{
  return nil,nil,err
}

privateKeySm2, ok := privateKey.(*sm2.PrivateKey)
if !ok {
  return nil,nil,errors.New("private key is not SM2 private key")
}

publicKeyBytes, err := ioutil.ReadFile(publicKeyPath)
if err != nil {
  return nil, nil, fmt.Errorf("failed to read public key file: %w",err)
}

publicKeyBlock, _:= pem.Decode(publicKeyBytes)

publicKey,err:=x509.ParsePKIXPublicKey(publickeyblock.Bytes)
if publicKey==nil{
  return nil,nil,err
}

publicKeySm2, ok := publicKey.(*sm2.PublicKey)
if !ok {
  return nil,nil,errors.New("public key is not SM2 public key")
}

return privateKeySm2, publicKeySm2, nil

}

func main() {

err := WriteKeyPairToFile("private.pem", "public.pem", []byte("1234"))
if err != nil {
	fmt.Println("秘钥对写入文件失败!")
	return
}

privateKey, publicKey, err := ReadKeyPairFromFile("private.pem", "public.pem")
if err != nil {
	fmt.Println("读取公钥私钥失败!")
	return
}

fileData, err := ioutil.ReadFile("E:/1.mp4")
if err != nil {
    fmt.Println("文件读取失败!")
    return

}

sigMsg,_ := sm2.Sign(rand.Reader,privatekey,filedata,nil)

ok:=sm2.Verify(pubkey,filedata,sigMsg)

if ok{
  fmt.Println("验证成功")
}else{
  fmt.Println("验证失败")

} }


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=12609

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?