Skip to content

Instantly share code, notes, and snippets.

@bradylove
Last active December 21, 2015 00:09
Show Gist options
  • Save bradylove/6217662 to your computer and use it in GitHub Desktop.
Save bradylove/6217662 to your computer and use it in GitHub Desktop.
Generates RSA KeyPair and writes to file in PEM format.
package main
import (
"crypto/rsa"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"os"
"fmt"
)
type KeyPair struct {
PublicKeyPEM string
PrivateKeyPEM string
}
func (this *KeyPair) Generate() {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
return
}
err = priv.Validate()
if err != nil {
fmt.Println("Validation failed:", err)
return
}
privDer := x509.MarshalPKCS1PrivateKey(priv)
privBlock := pem.Block {
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDer,
}
pub := priv.PublicKey
pubDer, err := x509.MarshalPKIXPublicKey(&pub)
if err != nil {
fmt.Println("Failed to get der format of PublicKey: ", err)
return
}
pubBlock := pem.Block {
Type: "RSA PUBLIC KEY",
Headers: nil,
Bytes: pubDer,
}
this.PrivateKeyPEM = string(pem.EncodeToMemory(&privBlock))
this.PublicKeyPEM = string(pem.EncodeToMemory(&pubBlock))
}
func (this *KeyPair) WriteToFile(filepath string) error {
file, err := os.Create(filepath)
if err != nil {
return err
}
defer file.Close()
file.WriteString(this.PublicKeyPEM)
file.WriteString(this.PrivateKeyPEM)
return nil
}
func main() {
keyPair := new(KeyPair)
keyPair.Generate()
fmt.Printf(keyPair.PublicKeyPEM)
fmt.Printf(keyPair.PrivateKeyPEM)
filepath := "testfile.pem"
err := keyPair.WriteToFile(filepath)
if err != nil {
fmt.Println("Unable to write", filepath)
} else {
fmt.Println("Successfull wrote", filepath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment