Generating RSA Keys with Go: Replicating Openssl genrsa
The OpenSSL command openssl genrsa -out $1.rsa $2 generates an RSA key pair and exports them to two separate files, $1.rsa for the private key and $1.rsa.pub for the public key. In Go, this process involves:
The following code demonstrates this process:
package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "io/ioutil" ) func main() { filename := "key" bitSize := 4096 key, err := rsa.GenerateKey(rand.Reader, bitSize) if err != nil { panic(err) } pub := key.Public() 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)), }, ) if err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700); err != nil { panic(err) } if err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755); err != nil { panic(err) } }
This code generates the private key file key.rsa and the public key file key.rsa.pub. The contents of these files resemble the output of the OpenSSL command.
The above is the detailed content of How Can I Generate RSA Key Pairs in Go, Mimicking OpenSSL's `genrsa` Command?. For more information, please follow other related articles on the PHP Chinese website!