Golang : Create x509 certificate, private and public keys
Instead of using openssl to generate public and private keys. Go can generate x509 certificates and equivalent RSA private/public keys as well. In this tutorial, we will learn how to use the crypto/x509
to create certificates and crypto/rsa
package to create private/public keys.
We will save the files with two methods. The first is with ioutil.WriteFile and followed by the GOB encoded files. You can compare the generated files and use the methods that you preferred for your codes.
Source code:
package main
import (
"time"
"os"
"encoding/gob"
"encoding/pem"
"math/big"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io/ioutil"
"crypto/rsa"
"crypto/rand"
)
func main() {
// ok, lets populate the certificate with some data
// not all fields in Certificate will be populated
// see Certificate structure at
// http://golang.org/pkg/crypto/x509/#Certificate
template := &x509.Certificate {
IsCA : true,
BasicConstraintsValid : true,
SubjectKeyId : []byte{1,2,3},
SerialNumber : big.NewInt(1234),
Subject : pkix.Name{
Country : []string{"Earth"},
Organization: []string{"Mother Nature"},
},
NotBefore : time.Now(),
NotAfter : time.Now().AddDate(5,5,5),
// see http://golang.org/pkg/crypto/x509/#KeyUsage
ExtKeyUsage : []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage : x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign,
}
// generate private key
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
}
publickey := &privatekey.PublicKey
// create a self-signed certificate. template = parent
var parent = template
cert, err := x509.CreateCertificate(rand.Reader, template, parent, publickey,privatekey)
if err != nil {
fmt.Println(err)
}
// save private key
pkey := x509.MarshalPKCS1PrivateKey(privatekey)
ioutil.WriteFile("private.key", pkey, 0777)
fmt.Println("private key saved to private.key")
// save public key
pubkey, _ := x509.MarshalPKIXPublicKey(publickey)
ioutil.WriteFile("public.key", pubkey, 0777)
fmt.Println("public key saved to public.key")
// save cert
ioutil.WriteFile("cert.pem", cert, 0777)
fmt.Println("certificate saved to cert.pem")
// these are the files save with encoding/gob style
privkeyfile, _ := os.Create("privategob.key")
privkeyencoder := gob.NewEncoder(privkeyfile)
privkeyencoder.Encode(privatekey)
privkeyfile.Close()
pubkeyfile, _ := os.Create("publickgob.key")
pubkeyencoder := gob.NewEncoder(pubkeyfile)
pubkeyencoder.Encode(publickey)
pubkeyfile.Close()
// this will create plain text PEM file.
pemfile, _ := os.Create("certpem.pem")
var pemkey = &pem.Block{
Type : "RSA PRIVATE KEY",
Bytes : x509.MarshalPKCS1PrivateKey(privatekey)}
pem.Encode(pemfile, pemkey)
pemfile.Close()
}
Reference : https://www.socketloop.com/tutorials/golang-saving-private-and-public-key-to-files
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+11.7k Android Studio : Password input and reveal password example
+14.1k Golang : Get query string value on a POST request
+12.7k Golang : Get current time
+7.7k Golang : Find duplicate files with filepath.Walk
+13.1k Golang : GUI with Qt and OpenCV to capture image from camera
+5.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+14k Golang : rune literal not terminated error
+3.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+14.8k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+7.8k Golang : Get final balance from bit coin address example
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot