本文主要是介绍国密GMSM2 —— go语言实现国密SM2加密算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package mainimport ("github.com/tjfoc/gmsm/sm2""fmt""encoding/hex"
)func main() {//生成私钥privateKey, e := sm2.GenerateKey()if e!=nil{fmt.Println("sm2 encrypt faild!")}//从私钥中获取公钥pubkey := &privateKey.PublicKeymsg:= []byte("i am wek && i am The_Reader too 。")//用公钥加密msgbytes, i := pubkey.Encrypt(msg)if i !=nil{fmt.Println("使用私钥加密失败!")}fmt.Println("the encrypt msg = ",hex.EncodeToString(bytes))//用私钥解密msgdecrypt, i2 := privateKey.Decrypt(bytes)if i2 != nil{fmt.Println("使用私钥解密失败!")}fmt.Println( "the msg = ", string(decrypt))}
结果为:
将密钥对写入文件并读出:
package mainimport ("github.com/tjfoc/gmsm/sm2""fmt"
)func writeKeyToFile(privKeyPath , pubKeyPath string , pass []byte){privateKey, e := sm2.GenerateKey()publicKey := &privateKey.PublicKeyif 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 ! ")}}
结果为:
这篇关于国密GMSM2 —— go语言实现国密SM2加密算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!