|

Generating RSA Private and Public Key Pair in Go Lang?

How to generate a pair of RSA private and public key in Go lang? Go lang has a rich set of standard libraries. Using Go’s standard libraries, we can generate RSA private and Public keys.

The Crypto standard libraries in Go lang

Go lang standard libraries has a rich set of cryptography functions. Here are some that we will use.

crypto/rsa

The package crypto/rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.

The func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) function generates an RSA keypair of the given bit size using the random source random (for example, crypto/rand.Reader, discussed below).

crypto/rand

The var Reader io.Reader struct is a global, shared instance of a cryptographically secure random number generator. On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise.

crypto/x509

The func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte function converts an RSA private key to PKCS #1, ASN.1 DER form. This kind of key is commonly encoded in PEM blocks of type “RSA PRIVATE KEY”.

The func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte function converts an RSA public key to PKCS #1, ASN.1 DER form. This kind of key is commonly encoded in PEM blocks of type “RSA PUBLIC KEY”.

encoding/pem

The func Encode(out io.Writer, b *Block) error function writes the PEM encoding of b to out.

The code to generate RSA private/public key pair in Go lang

With the above libraries available, we can generate a private/public key pair in Go lang by combining the Go lang standard libraries functions in a way like

rsa.GenerateKey() =>
x509.MarshalPKIXPublicKey() =>
pem.Encode()

We store the keys into a pair of files for the RSA private/public keys.

One example Go lang program is as follows.

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "fmt"
    "os"
)

func main() {
    // generate key
    privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        fmt.Printf("Cannot generate RSA key\n")
        os.Exit(1)
    }
    publickey := &privatekey.PublicKey

    // dump private key to file
    var privateKeyBytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)
    privateKeyBlock := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: privateKeyBytes,
    }
    privatePem, err := os.Create("private.pem")
    if err != nil {
        fmt.Printf("error when create private.pem: %s \n", err)
        os.Exit(1)
    }
    err = pem.Encode(privatePem, privateKeyBlock)
    if err != nil {
        fmt.Printf("error when encode private pem: %s \n", err)
        os.Exit(1)
    }

    // dump public key to file
    publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
    if err != nil {
        fmt.Printf("error when dumping publickey: %s \n", err)
        os.Exit(1)
    }
    publicKeyBlock := &pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: publicKeyBytes,
    }
    publicPem, err := os.Create("public.pem")
    if err != nil {
        fmt.Printf("error when create public.pem: %s \n", err)
        os.Exit(1)
    }
    err = pem.Encode(publicPem, publicKeyBlock)
    if err != nil {
        fmt.Printf("error when encode public pem: %s \n", err)
        os.Exit(1)
    }
}

Similar Posts

  • Latex is stuck with a strange problem, see more information for details.

    $ make pdflatex main.tex This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=pdflatex) restricted write18 enabled. entering extended mode (./main.tex LaTeX2e <2016/02/01> Babel <3.9q> and hyphenation patterns for 81 language(s) loaded. (/usr/share/texlive/texmf-dist/tex/latex/base/article.cls Document Class: article 2014/09/29 v1.4h Standard LaTeX document class (/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo)) (./usenix.sty (/usr/share/texlive/texmf-dist/tex/latex/psnfss/mathptmx.sty)) (/usr/share/texlive/texmf-dist/tex/latex/graphics/epsfig.sty (/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty (/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty) (/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty (/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty) (/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg) (/usr/share/texlive/texmf-dist/tex/latex/pdftex-def/pdftex.def (/usr/share/texlive/texmf-dist/tex/generic/oberdiek/infwarerr.sty) (/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ltxcmds.sty))))) (/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifpdf.sty)…

  • |

    How to enable user themes in Ubuntu 18.04?

    The way for Ubuntu 17 to installing the gnome-shell-extensions package does not work any more for Ubuntu 18.04. How to enable user themes in Ubuntu 18.04? The updated gnome-shell-extensions package actually adds the User Theme extension back. You can use that. First, install the package sudo apt install gnome-shell-extensions Second, log out and login again…

  • Direct multi-hop ssh connection

    How to use multi-hop ssh connection without needs to ssh multiple times? As a example, you are connecting to server.example.com through proxy.example.com from laptop.example.com as follows: laptop —-> proxy —-> server 2 possible methods: Method 1: Use the similar method as in Directly SSH to hosts using internal IPs through the gateway. Add this to…

  • Why I cannot login remote server with its root

    # ssh root@192.168.122.96 root@192.168.122.96’s password: Permission denied, please try again. Do according to [1]. NOTE: on Ubuntu, remember to restart ssh service like this “sudo restart ssh”. [1] https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/v2v_guide/preparation_before_the_p2v_migration-enable_root_login_over_ssh Read more: I cannot login Ubuntu Precise desktop ‘dd’ command cannot support calculation for its parameters How can I login without password and run command in…

Leave a Reply

Your email address will not be published. Required fields are marked *