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 ! ")
	}

}





 

结果为: