RSA cryptography in Golang

Let’s encrypt

(λx.x)eranga
Effectz.AI
2 min readAug 5, 2020

--

Background

In this post I’m gonna discuss about RSA cryptography functions in golang. All the source codes which related to this post available in gitlab. Please clone the repo and continue the post.

Key pair config

First I have defined the RSA key pair related configuration in config.go file. It contains the key pair location, key size parameters. I have used .keys directory inside the project root to store the keys. These configurations can be read with environment variables according to the 12FactorApps.

Crypto functions

Then I have defined the RSA cryptograph functions in crypto.go file. It contains functions for generate key pair, save keys on file, load keys from file, load keys from string, digitally sign, digital signature verification, encryption, decryption.

Main thing to notice here is getIdRsaPubFromStr function. This function is compatible to decode public keys which generated from Android/IOS mobile platforms. The public keys which generated from IOS platform needs to be unmarshal with asn1.Unmarshal. The default x509.ParsePKIXPublicKey not compatible with it. The getIdRsaPubFromStr function decode publicKey in both ways and choose the correct one.

Test functions

Following is the way to execute the functions defined in crypto.go from main.go file. When running it will generates the RSA keys on .keys directory inside project root.

Since multiple go files in the src directory, I need to build an executable from the files and run it. Following is the way to build and run the executable. The executable will be created in build directory.

Reference

  1. https://golangdocs.com/rsa-encryption-decryption-in-golang
  2. https://l1z2g9.github.io/2016/11/04/RSA-Encrypt-Decrypt-with-Golang/
  3. https://medium.com/rahasak/golang-logging-with-unix-logrotate-41ec2672b439
  4. https://medium.com/rahasak/dockerize-golang-application-a9bf34712c15

--

--