Skip to content

Instantly share code, notes, and snippets.

@devi
Created April 27, 2014 11:59
Show Gist options
  • Select an option

  • Save devi/11343897 to your computer and use it in GitHub Desktop.

Select an option

Save devi/11343897 to your computer and use it in GitHub Desktop.
Generate RSA key pair in PEM format
// Generate RSA key pair in PEM format.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"os"
)
var (
flagSize = flag.Int("size", 2048, "bit size")
flagPrivFile = flag.String("priv", "", "save private key to a file")
flagPubFile = flag.String("pub", "", "save public key to a file")
)
func main() {
flag.Parse()
priv, err := rsa.GenerateKey(rand.Reader, *flagSize)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = priv.Validate()
if err != nil {
fmt.Println("Validation failed.", err)
os.Exit(1)
}
privPem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
})
pubDer, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
if err != nil {
fmt.Println("Failed to get der format for PublicKey.", err)
os.Exit(1)
}
pubPem := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: pubDer,
})
if *flagPrivFile != "" {
pv, err := os.OpenFile(*flagPrivFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer pv.Close()
pv.Write(privPem)
} else {
fmt.Printf("%s\n", privPem)
}
if *flagPubFile != "" {
pb, err := os.OpenFile(*flagPubFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0664)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer pb.Close()
pb.Write(pubPem)
} else {
fmt.Printf("%s\n", pubPem)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment