國密GMSM2 —— go語言實現國密SM2加密演算法
阿新 • • 發佈:2018-11-25
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 ! ") } }
結果為: