Created
July 3, 2016 20:56
-
-
Save sdorra/83b063233918731d6aca250dcc64b00b to your computer and use it in GitHub Desktop.
Certificate generation in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"crypto/x509/pkix" | |
"encoding/pem" | |
"log" | |
"math/big" | |
"net" | |
"os" | |
"time" | |
) | |
func main() { | |
ip := "127.0.0.01" | |
hostname := "localhost" | |
priv, err := rsa.GenerateKey(rand.Reader, 2048) | |
if err != nil { | |
log.Fatalf("failed to generate rsa key: %s", err) | |
} | |
notBefore := time.Now() | |
notAfter := notBefore.Add(365 * 24 * time.Hour) | |
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) | |
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) | |
if err != nil { | |
log.Fatalf("failed to generate serial number: %s", err) | |
} | |
template := x509.Certificate{ | |
SerialNumber: serialNumber, | |
Subject: pkix.Name{ | |
Organization: []string{"Acme Co"}, | |
}, | |
NotBefore: notBefore, | |
NotAfter: notAfter, | |
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, | |
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, | |
BasicConstraintsValid: true, | |
IPAddresses: []net.IP{net.ParseIP(ip)}, | |
DNSNames: []string{hostname}, | |
} | |
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) | |
if err != nil { | |
log.Fatalf("Failed to create certificate: %s", err) | |
} | |
certOut, err := os.Create("cert.pem") | |
if err != nil { | |
log.Fatalf("failed to open cert.pem for writing: %s", err) | |
} | |
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) | |
certOut.Close() | |
log.Print("written cert.pem\n") | |
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) | |
if err != nil { | |
log.Print("failed to open key.pem for writing:", err) | |
return | |
} | |
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) | |
keyOut.Close() | |
log.Print("written key.pem\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment