国密GMSM2 —— go语言实现国密SM2加密算法

package main

import (
	"github.com/tjfoc/gmsm/sm2"
	"fmt"
	"encoding/hex"
)

func main() {

    //生成私钥
	privateKey, e := sm2.GenerateKey()
	if e!=nil{
		fmt.Println("sm2 encrypt faild!")
	}
    //从私钥中获取公钥
	pubkey := &privateKey.PublicKey

	msg:=  []byte("i am   wek &&  i am The_Reader too 。")
    //用公钥加密msg
	bytes, i := pubkey.Encrypt(msg)

	if i !=nil{
		fmt.Println("使用私钥加密失败!")
	}
    
	fmt.Println("the encrypt msg  =  ",hex.EncodeToString(bytes))
    //用私钥解密msg
	decrypt, i2 := privateKey.Decrypt(bytes)

	if i2 != nil{

		fmt.Println("使用私钥解密失败!")
	}

	fmt.Println( "the msg  = ", string(decrypt))

}

结果为:

 将密钥对写入文件并读出:

package main

import (
	"github.com/tjfoc/gmsm/sm2"
	"fmt"
)

func  writeKeyToFile(privKeyPath , pubKeyPath string , pass []byte){

	privateKey, e := sm2.GenerateKey()
	publicKey := &privateKey.PublicKey
	if e != nil{
		fmt.Println("获取密钥对失败!")
	}

	b, i := sm2.WritePrivateKeytoPem(privKeyPath, privateKey, pass)
	pem, i2 := sm2.WritePublicKeytoPem(pubKeyPath, publicKey, pass)

	if b||pem {
		fmt.Println("密钥已成功写入文件!")
	}else {
		fmt.Println("密钥对写入文件失败!")
	}
	if i != nil||i2 !=nil{
		fmt.Println("密钥对写入文件错误!!!")
	}

}

func readKeyFromFile(privKeyPath , pubKeyPath string , pass []byte)(*sm2.PrivateKey,*sm2.PublicKey,  bool){

	privateKey, e := sm2.ReadPrivateKeyFromPem(privKeyPath, pass)
	if e !=nil{
		return nil,nil,false
	}
	publicKey, i := sm2.ReadPublicKeyFromPem(pubKeyPath, pass)
	if i!=nil{
		return nil,nil,false
	}
	return privateKey,publicKey,true

}

func main() {
	//writeKeyToFile("./11_10/privateKey", "./11_10/publicKey", []byte("i am  wek && The_Reader "))
	privateKey, publicKey, b := readKeyFromFile("./11_10/privateKey", "./11_10/publicKey", []byte("i am  wek && The_Reader "))
	if b {

		fmt.Println("the privateKey is ",*privateKey,"\n")
		fmt.Println("the publicKey is ", *publicKey,"\n")
	}else {
		fmt.Println("readKeyFromFile Is Faild ! ")
	}

}





 

结果为:

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值