Use Go to Generate RSA Keys in the Same Way as Openssl
The OpenSSL command openssl genrsa generates a pair of RSA keys, storing the private key in one file and the public key in another. To achieve this functionality in Go, you can follow these steps:
import "crypto/rand" key, err := rsa.GenerateKey(rand.Reader, bitSize) if err != nil { panic(err) }
import "crypto/rsa" pub := key.Public()
import ( "encoding/pem" "crypto/x509" ) keyPEM := pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }, ) pubPEM := pem.EncodeToMemory( &pem.Block{ Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(pub.(*rsa.PublicKey)), }, )
import "io/ioutil" err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700) err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755)
This code will generate two files, filename.rsa and filename.rsa.pub, containing the private and public RSA keys respectively. The keys will be in the PEM format, which allows you to easily import and use them with other applications.
The above is the detailed content of How Can I Generate RSA Key Pairs in Go, Similar to OpenSSL's `openssl genrsa` Command?. For more information, please follow other related articles on the PHP Chinese website!