Skip to content

Instantly share code, notes, and snippets.

@export-mike
Created September 16, 2022 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save export-mike/4c9b07d1add9c6104403d6edf4276760 to your computer and use it in GitHub Desktop.
Save export-mike/4c9b07d1add9c6104403d6edf4276760 to your computer and use it in GitHub Desktop.
generate cert pem and key pem
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"time"
)
func main() {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal("Private key cannot be created.", err.Error())
}
// Generate a pem block with the private key
keyPem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
tml := x509.Certificate{
// you can add any attr that you need
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(5, 0, 0),
// you have to generate a different serial number each execution
SerialNumber: big.NewInt(123123),
Subject: pkix.Name{
CommonName: "New Name",
Organization: []string{"New Org."},
},
BasicConstraintsValid: true,
}
cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
if err != nil {
log.Fatal("Certificate cannot be created.", err.Error())
}
// Generate a pem block with the certificate
certPem := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
})
fmt.Println("keyPen", string(keyPem))
fmt.Println("certPem", string(certPem))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment