To generate a public-private key pair for asymmetric cryptography in Go, you can use the crypto
package's rsa
subpackage. Here's an example of how to do it:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
func main() {
// Generate a private key
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Printf("Failed to generate private key: %v", err)
return
}
// Extract the public key from the private key
publicKey := &privateKey.PublicKey
// Encode the private key to PEM format
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
// Write the private key PEM to a file
privateKeyFile, err := os.Create("private_key.pem")
if err != nil {
fmt.Printf("Failed to create private key file: %v", err)
return
}
defer privateKeyFile.Close()
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
fmt.Printf("Failed to write private key PEM: %v", err)
return
}
// Encode the public key to PEM format
publicKeyPEM, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
fmt.Printf("Failed to encode public key: %v", err)
return
}
// Write the public key PEM to a file
publicKeyFile, err := os.Create("public_key.pem")
if err != nil {
fmt.Printf("Failed to create public key file: %v", err)
return
}
defer publicKeyFile.Close()
if err := pem.Encode(publicKeyFile, &pem.Block{Type: "PUBLIC KEY", Bytes: publicKeyPEM}); err != nil {
fmt.Printf("Failed to write public key PEM: %v", err)
return
}
fmt.Println("Key pair generated successfully!")
}
This code will generate a 2048-bit RSA key pair and save the private key PEM to private_key.pem
and the public key PEM to public_key.pem
. You can adjust the key size according to your needs.