三国纷争
要生成 RSA 密钥对并将私钥和公钥写入单独的文件,您需要执行以下操作:使用rsa.GenerateKey生成 RSA 密钥对使用rsa.PrivateKey.Public获取公钥组件分别使用x509.MarshalPKCS1PrivateKey和x509.MarshalPKCS1PublicKey将密钥转换为 PKCS#1 ASN.1 DER 形式使用pem.EncodeToMemory编码成 PEM 块写出文件完整的操作集如下所示,其中filename和bitSize 分别是您的$1和$2参数。package mainimport ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "io/ioutil")func main() { filename := "key" bitSize := 4096 // Generate RSA key. key, err := rsa.GenerateKey(rand.Reader, bitSize) if err != nil { panic(err) } // Extract public component. pub := key.Public() // Encode private key to PKCS#1 ASN.1 PEM. keyPEM := pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }, ) // Encode public key to PKCS#1 ASN.1 PEM. pubPEM := pem.EncodeToMemory( &pem.Block{ Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(pub.(*rsa.PublicKey)), }, ) // Write private key to file. if err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700); err != nil { panic(err) } // Write public key to file. if err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755); err != nil { panic(err) }}这将生成以下两个文件:密钥.rsa:-----BEGIN RSA PRIVATE KEY-----MIIJJwIBAAKCAgEAsmJ+97V6zCOQdXDd0pivvgoXynKAHaImVdafXDwN+Eb2xKTgzjhthm144DZzO9/SllCdyLwhXKBQkgim2S5A4iV5w6/yvChqL72+BrItP0+1tAgYvt/CcShDtMdSikW13BN3+SGZSP9yrEsdU2KMK6HSGcSxMpki/XW2BbGkdr3gMtpM...S8tZZ/gby/k9nG7Pbw55QM8/Jkyvy/lPP94HrE+MuIiTEd9BG4c7CRNIuE6QoCjp1+NIbqEPJTJMfH57cx8R/stLh2nBGcngjmWz+VWhufzhsOr7Wl8Xd6hf13hm4hWGy+2pknoTGvw05tiU/eLAbNimtWMOtEdfePzT5NTjV++9kJSr470eyDs2bg==-----END RSA PRIVATE KEY-----key.rsa.pub:-----BEGIN RSA PUBLIC KEY-----MIICCgKCAgEAsmJ+97V6zCOQdXDd0pivvgoXynKAHaImVdafXDwN+Eb2xKTgzjhthm144DZzO9/SllCdyLwhXKBQkgim2S5A4iV5w6/yvChqL72+BrItP0+1tAgYvt/C...8Xil1cP/5LxIMa1WGHEG1jzrWJkyaVXHS0JOi3FcI4KPQttut2rWpSi3MtAlmuTxk/AfM3oNnAUlcjYNa+onSs7GgLhd1A5/EiLGMR304uWKno8HrYQfESsCAwEAAQ==-----END RSA PUBLIC KEY-----我建议您熟悉链接的功能,它们的文档非常有用。还有其他可用的格式选项(例如:PKCS#8 和 PKIX)以及用于私钥的加密 PEM。