Created
September 16, 2022 01:28
-
-
Save export-mike/4c9b07d1add9c6104403d6edf4276760 to your computer and use it in GitHub Desktop.
generate cert pem and key pem
This file contains hidden or 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" | |
"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