golang產生RSA的公鑰以及私鑰
阿新 • • 發佈:2018-12-18
package main import ( "crypto/rsa" "crypto/rand" "fmt" "crypto/x509" "encoding/pem" "os" ) func main() { key, err := rsa.GenerateKey(rand.Reader, 128) if err!=nil { fmt.Println(err) } //生成私鑰 pkcs1PrivateKey := x509.MarshalPKCS1PrivateKey(key) block:=&pem.Block{ Type:"RSA PRIVATE KEY", Bytes:pkcs1PrivateKey, } //寫入檔案 file, err := os.Create("private.pem") pem.Encode(file,block) //產生公鑰 主要取地址 PublicKey := &key.PublicKey //公鑰從私鑰中產生 pkixPublicKey, err := x509.MarshalPKIXPublicKey(PublicKey) block1:=&pem.Block{ Type:"RSA PUBLIC KEY", Bytes:pkixPublicKey, } file2, err := os.Create("public.pem") encode := pem.Encode(file2, block1) fmt.Println(encode) }