The openssl command genrsa generates RSA keys. We can achieve the same functionality in Go using the crypto/rsa package. This article provides a detailed walkthrough of how to generate RSA key pairs and write them to separate files in Go.
import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "io/ioutil" )
filename := "key" bitSize := 4096 // Generate RSA keypair key, err := rsa.GenerateKey(rand.Reader, bitSize)
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) }
By following the steps outlined above, you can effortlessly generate RSA key pairs and write them to separate files in Go, similar to the openssl genrsa command. This comprehensive guide provides a solid foundation for working with RSA keys in your Go applications.
The above is the detailed content of How to Generate RSA Key Pairs in Go and Write Them to Separate Files?. For more information, please follow other related articles on the PHP Chinese website!