Understanding the Openssl Command
The provided OpenSSL command generates an RSA key pair and saves the private and public keys to separate files. It takes two arguments:
Implementing in Go
To replicate this functionality in Go, we need to perform the following steps:
Go Code:
package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" ) func main() { // Define filename and bit size filename := "key" bitSize := 4096 // Generate RSA key key, err := rsa.GenerateKey(rand.Reader, bitSize) if err != nil { panic(err) } // Extract public key pub := key.Public() // Convert to PKCS#1 DER format 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)), }, ) // Write keys to files err = ioutil.WriteFile(filename+".rsa", keyPEM, 0700) if err != nil { panic(err) } err = ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755) if err != nil { panic(err) } fmt.Println("RSA key pair generated and written to files.") }
Output:
The program will create two files with the following contents:
key.rsa:
-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----
key.rsa.pub:
-----BEGIN RSA PUBLIC KEY----- ... -----END RSA PUBLIC KEY-----
The above is the detailed content of How to Generate RSA Key Pairs in Go: A Comparison with OpenSSL?. For more information, please follow other related articles on the PHP Chinese website!