Go Language - RSA Encryption And Decryption PKCS Example

The RSA algorithm (Rivest-Shamir-Adleman) is a cryptographic algorithm that is used for specific security services or purposes, which enables public-key encryption and is widely used to secure sensitive data, particularly when it is being sent over an insecure network such as the HTTP. A public key is shared publicly, while a private key is secret and must not be shared with anyone.

The following illustration highlights how asymmetric cryptography works:

RSA Encryption and Decryption with PKCS1v15 Example,

package main

//Required imports for Encryption & Decryption
import (

func main() {

//2048 is the number of bits for RSA
bitSize := 2048

//Generate RSA keys
privateKey, err := rsa.
GenerateKey(rand.Reader, bitSize)
if err != nil {

publicKey := privateKey.PublicKey

//Your secret text
secretMessage := "My Secret Text"

encryptedMessage := Encrypt(secretMessage, publicKey)

//Print Cipher Text on the console
fmt.Println("Cipher Text:", encryptedMessage)

Decrypt(encryptedMessage, *privateKey)

//Encryption with PKCS1v15 padding
func Encrypt(secretMessage string,
key rsa.PublicKey) string {
rng := rand.Reader
pkc, errs := rsa.EncryptPKCS1v15(rng, &key,

if errs != nil {

return base64.StdEncoding.EncodeToString(pkc)

func Decrypt(cipherText string,
privKey rsa.PrivateKey) string {

//Decode the Cipher text
ct, err := base64.StdEncoding.DecodeString(cipherText)
rng := rand.Reader

text, err := rsa.DecryptPKCS1v15(rng, &privKey, ct)

if err != nil {

//Print secret text on the console
fmt.Println("Plaintext:", string(text))
return string(text)

Run the application:

go run rsapkcsdemo.go

                                                                         Author name,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example