Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang RSA Key Generation
/*
* Genarate rsa keys.
*/
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/gob"
"encoding/pem"
"fmt"
"os"
)
func main() {
reader := rand.Reader
bitSize := 2048
key, err := rsa.GenerateKey(reader, bitSize)
checkError(err)
publicKey := key.PublicKey
saveGobKey("private.key", key)
savePEMKey("private.pem", key)
saveGobKey("public.key", publicKey)
savePublicPEMKey("public.pem", publicKey)
}
func saveGobKey(fileName string, key interface{}) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()
encoder := gob.NewEncoder(outFile)
err = encoder.Encode(key)
checkError(err)
}
func savePEMKey(fileName string, key *rsa.PrivateKey) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()
var privateKey = &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
err = pem.Encode(outFile, privateKey)
checkError(err)
}
func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) {
asn1Bytes, err := asn1.Marshal(pubkey)
checkError(err)
var pemkey = &pem.Block{
Type: "PUBLIC KEY",
Bytes: asn1Bytes,
}
pemfile, err := os.Create(fileName)
checkError(err)
defer pemfile.Close()
err = pem.Encode(pemfile, pemkey)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}
@Engelch

This comment has been minimized.

Copy link

@Engelch Engelch commented May 28, 2017

brilliant example, exactly to the point.

@Xeoncross

This comment has been minimized.

Copy link

@Xeoncross Xeoncross commented Jun 14, 2017

You can also replace asn1Bytes, err := asn1.Marshal(pubkey) with asn1Bytes, err := x509.MarshalPKIXPublicKey(&pubkey) if you want DER-encoded PKIX format.

@irshadhasmat

This comment has been minimized.

Copy link

@irshadhasmat irshadhasmat commented Nov 22, 2017

A fantastic example. Very precise...

Thanks.

@helmutkemper

This comment has been minimized.

Copy link

@helmutkemper helmutkemper commented Dec 20, 2017

In fact, for the code to work properly, the change suggested by Xeoncross must be made.

Thank you all

@JitinGuglani

This comment has been minimized.

Copy link

@JitinGuglani JitinGuglani commented Feb 1, 2018

if any one knows how to save in .der format ?

@johnwesley

This comment has been minimized.

Copy link

@johnwesley johnwesley commented Apr 28, 2018

Very well done, thank you. The only thing I would add are permissions on the private key file for ssh.

@oscarzhou

This comment has been minimized.

Copy link

@oscarzhou oscarzhou commented Jun 6, 2018

Awesome example. Thanks

@ugokoli

This comment has been minimized.

Copy link

@ugokoli ugokoli commented May 17, 2019

Nice, but fails when using the generated public key to verify jwt token with https://github.com/dgrijalva/jwt-go. @Xeoncross comment fixes the error.

@muratsplat

This comment has been minimized.

Copy link

@muratsplat muratsplat commented Jun 14, 2019

@sdorra Why does the code example generate same private and public key while the code is executing one more time ?

@Xeoncross

This comment has been minimized.

Copy link

@Xeoncross Xeoncross commented Jun 14, 2019

@muratsplat If you run it on play.golang.org it will always produce the same result. If you don't check the errors you might find that O_CREATE fails on the second run because the file already exists.

@muratsplat

This comment has been minimized.

Copy link

@muratsplat muratsplat commented Jun 14, 2019

Sorry I forgot the test result is cached on the test. That reason make to show same result. You are right.

@muratsplat

This comment has been minimized.

Copy link

@muratsplat muratsplat commented Jun 14, 2019

@Xeoncross thanks for feedback..

@zzbennett

This comment has been minimized.

Copy link

@zzbennett zzbennett commented Nov 20, 2020

Amazing! This and the comments saved me a bunch of time implementing this, especially @ugokoli's comment about jwt-go

@soxfmr

This comment has been minimized.

Copy link

@soxfmr soxfmr commented Jan 18, 2021

For PKCS#1 Formatting, the lable should be starts with RSA PRIVATE KEY instead of PRIVATE KEY. Nice code snippets 😃

var privateKey = &pem.Block{
    Type:  "RSA PRIVATE KEY",
    Bytes: x509.MarshalPKCS1PrivateKey(key),
}
@Dancheg97

This comment has been minimized.

Copy link

@Dancheg97 Dancheg97 commented May 6, 2021

yo man, after a single look at your code i felt like it's really beatiful and ... i love u bruh thx for that implementation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment