Golang : Saving private and public key to files
In this tutorial we will learn how to save the RSA private and public keys to files. We will use RSA in this tutorial, but you can use this tutorial for saving other type of encryption system private and public keys.
Without further ado :
saversafiles.go
package main
import (
"os"
"fmt"
"crypto/rand"
"crypto/rsa"
"encoding/gob"
"encoding/pem"
"crypto/x509"
)
func main() {
// generate private key
privatekey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
fmt.Println(err.Error)
os.Exit(1)
}
var publickey *rsa.PublicKey
publickey = &privatekey.PublicKey
// save private and public key separately
privatekeyfile, err := os.Create("private.key")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
privatekeyencoder := gob.NewEncoder(privatekeyfile)
privatekeyencoder.Encode(privatekey)
privatekeyfile.Close()
publickeyfile, err := os.Create("public.key")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
publickeyencoder := gob.NewEncoder(publickeyfile)
publickeyencoder.Encode(publickey)
publickeyfile.Close()
// save PEM file
pemfile, err := os.Create("private.pem")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// http://golang.org/pkg/encoding/pem/#Block
var pemkey = &pem.Block{
Type : "RSA PRIVATE KEY",
Bytes : x509.MarshalPKCS1PrivateKey(privatekey)}
err = pem.Encode(pemfile, pemkey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
pemfile.Close()
}
Note : The repeatable codes can be converted to function for easier calling.
Sample output of private.pem :
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC9/H127GOFgwROUPTGdpw6fCL5DGvpldLALkr6o7ia/6mvioVT
B+ivUwgo/WXyIHHPEtKNtnKH4OUcav/TNiXDqV+q9ybZ6SCodHPtryJzyy3iMhRz
9WxfAlKrF+XmiC8hzJsXjfE3o0sjacrEdlxn+zmxu5H2weSFh4ZjXCBtzQIDAQAB
AoGAe1QfYga76ByPvAMjkn3GltSko0Uj/CMNB0JF3ARRvxR9430pZSf6LW3aGzm7
Zv0WxBR06Bdqq7gbImJ3JXW99vAqUUseLuR6KQ78YvZDkNz4aKnXCFBvJmtCVTj9
SPyY0KoKjeR7slgdik0CbrisqrlFOk+eO9Bj7Wd40p14SGECQQDCUp2/t9qS5v1O
C+1xkRZ+BDJ1+WBoGHDXFPVchbfYdZSHtlurTEdN8g4MaHohY7d7/QFUJSXOh4M8
utS0TmTpAkEA+kmGLrrAO+SDNJMcNi/w+m1qO1o3acewUbZI04tyqon583O+rVzB
Lo3iTbErKTK/1HA0+Brqjp7xe6lS0PyDRQJARjdWGw2TJFvlEcuLi+rSRsy7cxee
N18FfyJqmnkS+ltaRUOmkhoo9chOPTuPTftbNKkyTrZxl9Qtnscfzts46QJBAIf2
/Q/Rn7BpmOUsrXy6WnyQh88qWUP7mMsq7TEOZgJC5ifczs66vq8doLx37Gx7Bz7O
ndfSN2225pQ5DaY+JskCQHIrr7XOX0Ka0FmZcyvsDI0YzySvATrDnYxa3gj4YBSW
eaV15LvMgibF3khLjXsuR8kUNd58NB/uAyeXuGrF2sI=
-----END RSA PRIVATE KEY-----
Reference :
https://code.google.com/p/go/source/browse/src/pkg/encoding/pem/pem_test.go
See also : Golang : Example for RSA package functions
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
+15.5k Golang : rune literal not terminated error
+11.5k Swift : Convert (cast) Float to String
+21.4k Golang : How to read float value from standard input ?
+32.3k Golang : Math pow(the power of x^y) example
+4.7k PHP : Extract part of a string starting from the middle
+13.9k Golang : concatenate(combine) strings
+16k Golang : How to reverse elements order in map ?
+6.9k Nginx : Password protect a directory/folder
+40.9k Golang : How to check if a string contains another sub-string?
+19.4k Golang : How to Set or Add Header http.ResponseWriter?
+18k Golang : Check if a directory exist or not
+6k Golang : Missing Subversion command