Skip to content

Instantly share code, notes, and snippets.

@mori-dev
Created August 28, 2017 03:13
Show Gist options
  • Save mori-dev/abbb8d65c80b2d581a62847bcaf6c39a to your computer and use it in GitHub Desktop.
Save mori-dev/abbb8d65c80b2d581a62847bcaf6c39a to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io"
"log"
"os"
)
func main() {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
privDer := x509.MarshalPKCS1PrivateKey(priv)
if err != nil {
log.Fatal(err)
}
pubkey := priv.Public()
pubDer, err := x509.MarshalPKIXPublicKey(pubkey)
if err != nil {
log.Fatal(err)
}
pemblock := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: privDer}
pubblock := &pem.Block{Type: "RSA PUBLIC KEY", Bytes: pubDer}
privFile, err := os.OpenFile("./rsa_keys/foo_rsa", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer close(privFile)
pubFile, err := os.OpenFile("./rsa_keys/foo_rsa.pub", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer close(pubFile)
if err != nil {
log.Fatal(err)
}
err = pem.Encode(privFile, pemblock)
if err != nil {
log.Fatal(err)
}
err = pem.Encode(pubFile, pubblock)
if err != nil {
log.Fatal(err)
}
}
func close(c io.Closer) {
err := c.Close()
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment