Skip to content

Instantly share code, notes, and snippets.

@bboozzoo
Last active May 19, 2016 07:47
Show Gist options
  • Save bboozzoo/4925e3a0e727c36b19165ec5f41c084f to your computer and use it in GitHub Desktop.
Save bboozzoo/4925e3a0e727c36b19165ec5f41c084f to your computer and use it in GitHub Desktop.
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"log"
"os"
)
const (
pubfilename = "gokeypub.pem"
privfilename = "gokey.pem"
)
func toFile(name string, block *pem.Block) {
f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatalf("failed to open priv")
}
pem.Encode(f, block)
f.Close()
}
func main() {
priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
log.Printf("key generation failed: %s")
os.Exit(1)
}
privbytes, _ := x509.MarshalECPrivateKey(priv)
pubbytes, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
log.Printf("saving public key to %s", pubfilename)
toFile(pubfilename, &pem.Block{
Type: "PUBLIC KEY",
Bytes: pubbytes,
})
log.Printf("saving private key to %s", privfilename)
toFile(privfilename, &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: privbytes,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment