Skip to content

Instantly share code, notes, and snippets.

@sdorra
Created April 17, 2016 19:31
Show Gist options
  • Save sdorra/1c95de8cb80da31610d2ad767cd6f251 to your computer and use it in GitHub Desktop.
Save sdorra/1c95de8cb80da31610d2ad767cd6f251 to your computer and use it in GitHub Desktop.
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)
}
}
@muratsplat
Copy link

@xeoncross thanks for feedback..

@zzbennett
Copy link

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

@soxfmr
Copy link

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),
}

@d1nch8g
Copy link

d1nch8g 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!

@GaureeshAnvekar
Copy link

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

Thanks a lot

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