Encryption examples

There are two primary scenarios in which encryption is required when interfacing with the API, as outlined below:

  • To protect sensitive card related information such as card PAN (long card number), PIN or CVV2 numbers while in transit. For this scenario, AES-256 symmetric encryption is used.
  • For partners using a PKI based integration there are two additional requirements, both of which employ RSA PKCS#1 encryption and are explained in the PKI integration guide :
    • To encrypt and decrypt sensitive API usage-related fields such as partner passwords and encryption keys sent to/from the API.
    • To digitally sign HTTPS requests to the API, and to verify their respective responses.
info

Code examples for Java and C# utilize the Bouncy Castle crypto and encryption library.

AES-256 symmetric encryption and decryption examples

PythonPHPJavascriptJavaRubyC#Go
Copy
Copied
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import base64

def aes256encrypt(payload: str, aes_key: str):
    iv = bytes.fromhex(aes_key[:32])
    key = bytes.fromhex(aes_key[32:96])

    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_payload = padder.update(payload.encode('utf-16le')) + padder.finalize()

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()

    encrypted = encryptor.update(padded_payload) + encryptor.finalize()

    return base64.b64encode(encrypted).decode('utf-8')

def aes256decrypt(payload: str, aes_key: str):
    iv = bytes.fromhex(aes_key[:32])
    key = bytes.fromhex(aes_key[32:96])

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()

    decrypted = decryptor.update(base64.b64decode(payload)) + decryptor.finalize()

    unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
    unpadded_decrypted = unpadder.update(decrypted) + unpadder.finalize()

    return unpadded_decrypted.decode('utf-16le')


plainText = '1234567890123456'
aes_key = '9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2'

encryptedText = aes256encrypt(plainText, aes_key)
print(encryptedText)
decryptedText = aes256decrypt(encryptedText, aes_key)
print(decryptedText)
Copy
Copied
<?php

function encrypt($data, $aes_key) {
    $data = mb_convert_encoding($data, 'UTF-16LE');
    $key = hex2bin(substr($aes_key,32,96));
    $iv = hex2bin(substr($aes_key,0,32));
    $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($encrypted);
}

function decrypt($data, $aes_key) {
    $data = base64_decode($data);
    $key = hex2bin(substr($aes_key,32,96));
    $iv = hex2bin(substr($aes_key,0,32));
    $decrypted = openssl_decrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return mb_convert_encoding($decrypted, 'UTF-8', 'UTF-16LE');
}


$plainText = "1234567890123456";
$aes_key = "9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2";

$encryptedText = encrypt($plainText, $aes_key);
echo $encryptedText . "\n";
$decryptedText = decrypt($encryptedText, $aes_key);
echo $decryptedText;

?>
Copy
Copied
const crypto = require('crypto');

function aes256encrypt(payload, aes_key) {
    var iv = Buffer.from(aes_key.slice(0,32), 'hex');
    var key = Buffer.from(aes_key.slice(32,96), 'hex');

    // Encrypting
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(
    payload.toString(),
        'utf16le',
        'base64'
    );
    encrypted += cipher.final('base64');

    return encrypted;
};

function aes256decrypt(payload, aes_key) {
    var iv = Buffer.from(aes_key.slice(0,32), 'hex');
    var key = Buffer.from(aes_key.slice(32,96), 'hex');

    // Decrypting
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(payload, 'base64', 'utf16le');
    decrypted += decipher.final('utf16le');

    return decrypted;
};

const plainText = "1234567890123456";
const aes_key = "9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2";
encryptedText = aes256encrypt(plainText, aes_key);
console.log("Encrypted: " + encryptedText);
decryptedText = aes256decrypt(encryptedText, aes_key);
console.log("Decrypted: " + decryptedText);
Copy
Copied
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


public class AES256EncryptDecrypt {
	
	public static void main(String[] args) {
		String message = "1234567890123456";
		String aes_key = "9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2";

		try {
		    String encryptedValue = AesCbcEncryptor.encrypt(message, aes_key);
		    System.out.println("Encrypted value: " + encryptedValue);
		    
		    String decryptedValue = AesCbcDecryptor.decrypt(encryptedValue, aes_key);
		    System.out.println("Decrypted value: " + decryptedValue);
		} catch (Exception e) {
		    e.printStackTrace();
		}
	}
	
	public class AesCbcEncryptor {
	    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
	    private static final String KEY_ALGORITHM = "AES";
	    private static final int KEY_SIZE = 256;
	    private static final int IV_SIZE = 16;

	    public static String encrypt(String message, String aes_key) throws Exception {
	        byte[] messageBytes = message.getBytes(StandardCharsets.UTF_16LE);
	        byte[] keyBytes = hexStringToByteArray(aes_key.substring(32,96));
	        byte[] ivBytes = hexStringToByteArray(aes_key.substring(0,32));

	        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
	        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

	        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
	        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

	        byte[] encryptedBytes = cipher.doFinal(messageBytes);
	        return Base64.getEncoder().encodeToString(encryptedBytes);
	    }

	    private static byte[] hexStringToByteArray(String hexString) {
	        int len = hexString.length();
	        byte[] data = new byte[len / 2];
	        for (int i = 0; i < len; i += 2) {
	            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
	                    + Character.digit(hexString.charAt(i + 1), 16));
	        }
	        return data;
	    }
	}
	
	public class AesCbcDecryptor {
	    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
	    private static final String KEY_ALGORITHM = "AES";
	    private static final int KEY_SIZE = 256;
	    private static final int IV_SIZE = 16;

	    public static String decrypt(String encryptedValue, String aes_key) throws Exception {
	        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedValue);
	        byte[] keyBytes = hexStringToByteArray(aes_key.substring(32,96));
	        byte[] ivBytes = hexStringToByteArray(aes_key.substring(0,32));

	        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
	        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

	        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
	        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

	        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
	        return new String(decryptedBytes, StandardCharsets.UTF_16LE);
	    }

	    private static byte[] hexStringToByteArray(String hexString) {
	        int len = hexString.length();
	        byte[] data = new byte[len / 2];
	        for (int i = 0; i < len; i += 2) {
	            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
	                    + Character.digit(hexString.charAt(i + 1), 16));
	        }
	        return data;
	    }
	}
}
Copy
Copied
require 'openssl'
require 'base64'

def aes256encrypt(payload, aes_key)
  iv = aes_key.slice(0, 32).scan(/../).map { |x| x.hex.chr }.join
  key = aes_key.slice(32, 64).scan(/../).map { |x| x.hex.chr }.join

  # Encrypting
  cipher = OpenSSL::Cipher.new('aes-256-cbc')
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv
  encrypted = cipher.update(payload.encode('utf-16le')) + cipher.final

  Base64.encode64(encrypted)
end

def aes256decrypt(payload, aes_key)
  iv = aes_key.slice(0, 32).scan(/../).map { |x| x.hex.chr }.join
  key = aes_key.slice(32, 64).scan(/../).map { |x| x.hex.chr }.join

  # Decrypting
  decipher = OpenSSL::Cipher.new('aes-256-cbc')
  decipher.decrypt
  decipher.key = key
  decipher.iv = iv
  decrypted = decipher.update(Base64.decode64(payload)) + decipher.final

  decrypted.force_encoding('utf-16le').encode('utf-8')
end

# Example usage
plain_text = "1234567890123456"
aes_key = "9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2"

# Encrypt the plain text and encode the result in Base64 format
encrypted_text = aes256encrypt(plain_text, aes_key)
puts "Encrypted: " + encrypted_text

# Decrypt the Base64-encoded encrypted text
decrypted_text = aes256decrypt(encrypted_text, aes_key)
puts "Decrypted: " + decrypted_text
Copy
Copied
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;public class AES256EncryptDecrypt
{
    public byte[] FromHexString(String hex)
    {
        byte[] bts = new byte[hex.Length / 2];
        for (int i = 0; i < bts.Length; i++)
        {
            bts[i] = (byte)Convert.ToInt32(hex.Substring(2 * i, 2), 16);
        }
        return bts;
    }
    
    public string Encrypt(string PlainValue, string securityKey)
    {
        byte[] iv = FromHexString(securityKey.Remove(32, 64));
        byte[] key = FromHexString(securityKey.Remove(0, 32));
        return AES256Encrypt(PlainValue, key, iv);
    }public string AES256Encrypt(string clearText, byte[] key, byte[] iv)
    {
        try
        {
            AesCryptoServiceProvider aesCipher = new AesCryptoServiceProvider();
            byte[] plainText = System.Text.Encoding.Unicode.GetBytes(clearText);
            ICryptoTransform encryptor = aesCipher.CreateEncryptor(key, iv);
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                //Defines a stream that links data streams to cryptographic transformations   
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    csEncrypt.Write(plainText, 0, plainText.Length);
                    //Writes the final state and clears the buffer   
                    csEncrypt.FlushFinalBlock();
                    byte[] cipherBytes = msEncrypt.ToArray();
                    string encryptedData = Convert.ToBase64String(cipherBytes);
                    return encryptedData;
                }
            }
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }public string Decrypt(string PlainValue, string securityKey)
    {
        byte[] iv = FromHexString(securityKey.Remove(32, 64));
        byte[] key = FromHexString(securityKey.Remove(0, 32));
        return AES256Decrypt(PlainValue, key, iv);
    }public string AES256Decrypt(string encrpytedText, byte[] key, byte[] iv)
    {
        try
        {
            AesCryptoServiceProvider aesCipher = new AesCryptoServiceProvider();
            byte[] encryptedData = Convert.FromBase64String(encrpytedText);
            ICryptoTransform decryptor = aesCipher.CreateDecryptor(key, iv);
            using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
            {
                //Defines the cryptographic stream for decryption.The stream contains decrypted data   
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    byte[] plainText = new byte[encryptedData.Length];
                    int decryptedCount = csDecrypt.Read(plainText, 0, plainText.Length);
                    string decryptedData = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    return decryptedData;
                }
            }
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }public static void Main()
    {
        string aes_key = "5433340f3e854875acb22ed5f5a3c96136089f0345aa4a00b634080d5c43b10af8af6dd63ad74b7d86a56f9d2314a700";
        string plainText = "1234567890123456";
        string encryptedValue, decryptedValue;AES256EncryptDecrypt encdec = new AES256EncryptDecrypt();
        encryptedValue = encdec.Encrypt(plainText, aes_key);
        decryptedValue = encdec.Decrypt(encryptedValue, aes_key);
​
        Console.WriteLine(encryptedValue);
        Console.WriteLine(decryptedValue);
    }
}
Copy
Copied
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/binary"
	"errors"
	"fmt"
	"strings"
)

func aes256encrypt(payload string, aesKey string) (string, error) {
	if len(aesKey) != 96 {
		return "", errors.New("AES key must be 96 characters long (IV + Key)")
	}

	key, err := hexToBytes(aesKey[32:])
	if err != nil {
		return "", err
	}

	iv, err := hexToBytes(aesKey[:32])
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	// Encode payload in 'utf-16le'
	utf16Payload := utf16Encode(payload)

	paddedPayload := pkcs7Pad(utf16Payload, aes.BlockSize)

	mode := cipher.NewCBCEncrypter(block, iv)
	ciphertext := make([]byte, len(paddedPayload))
	mode.CryptBlocks(ciphertext, paddedPayload)

	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func aes256decrypt(payload string, aesKey string) (string, error) {
	if len(aesKey) != 96 {
		return "", errors.New("AES key must be 96 characters long (IV + Key)")
	}

	key, err := hexToBytes(aesKey[32:])
	if err != nil {
		return "", err
	}

	iv, err := hexToBytes(aesKey[:32])
	if err != nil {
		return "", err
	}

	ciphertext, err := base64.StdEncoding.DecodeString(payload)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	mode := cipher.NewCBCDecrypter(block, iv)
	plaintext := make([]byte, len(ciphertext))
	mode.CryptBlocks(plaintext, ciphertext)

	unpadded, err := pkcs7Unpad(plaintext)
	if err != nil {
		return "", err
	}

	// Decode payload from 'utf-16le'
	decodedPayload := utf16Decode(unpadded)

	return decodedPayload, nil
}

func utf16Encode(s string) []byte {
	encoded := make([]byte, 2*len(s))
	for i, r := range s {
		binary.LittleEndian.PutUint16(encoded[i*2:], uint16(r))
	}
	return encoded
}

func utf16Decode(encoded []byte) string {
	runes := make([]rune, len(encoded)/2)
	for i := 0; i < len(runes); i++ {
		runes[i] = rune(binary.LittleEndian.Uint16(encoded[i*2:]))
	}
	return string(runes)
}

func hexToBytes(hexString string) ([]byte, error) {
	hexString = strings.ReplaceAll(hexString, " ", "")
	hexString = strings.ReplaceAll(hexString, "\n", "")
	hexString = strings.ToLower(hexString)

	if len(hexString)%2 != 0 {
		return nil, errors.New("hex input length must be even")
	}

	bytes := make([]byte, len(hexString)/2)
	for i := 0; i < len(hexString); i += 2 {
		_, err := fmt.Sscanf(hexString[i:i+2], "%02x", &bytes[i/2])
		if err != nil {
			return nil, err
		}
	}

	return bytes, nil
}

func pkcs7Pad(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padText...)
}

func pkcs7Unpad(data []byte) ([]byte, error) {
	length := len(data)
	if length == 0 {
		return nil, errors.New("input data is empty")
	}
	padding := int(data[length-1])
	if padding > length {
		return nil, errors.New("invalid padding")
	}
	return data[:length-padding], nil
}

func main() {
	plainText := "1234567890123456"
	aesKey := "9892cd73dc8f4036aefd16a6d96bcb6c6f4db5d44f11402a9fc89988c617060d77c3ce57004a4ba49e4316c5257b4dd2"

	encryptedText, err := aes256encrypt(plainText, aesKey)
	if err != nil {
		fmt.Println("Encryption error:", err)
		return
	}
	fmt.Println(encryptedText)

	decryptedText, err := aes256decrypt(encryptedText, aesKey)
	if err != nil {
		fmt.Println("Decryption error:", err)
		return
	}
	fmt.Println(decryptedText)
}

RSA PKCS#1 asymmetric encryption and decryption examples

Used for securing PKI based API access and digital signature generation and verification.

PythonPHPJavascriptJavaRubyC#Go
Copy
Copied
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from base64 import b64decode,b64encode

private_key = """-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW
XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds
3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFDlONfqu1BDxhl4/2CZaaK6LwrLaKc
IxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyFFkNsoyX/Et0KldT0qWCsTexf3QON
PbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aOGaZLhGSrNufaQUCQOfWaBD4vcDcI
i+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnPAgMBAAECggEAEB4RP6Th6iJzT1DT
cNaX0tddt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1LmV8J+Ox2jID1nc
2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv
BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz
-----END RSA PRIVATE KEY-----"""

public_key = """-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM
K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce
z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD
lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF
FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO
GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP
AgMBAAE=
-----END PUBLIC KEY-----"""

# encrypt data
def encryptData(data: str, rsa_key: str):
    key = RSA.import_key(rsa_key)

    cipher = Cipher_PKCS1_v1_5.new(key)
    cipher_text = cipher.encrypt(data.encode())

    b64encrypted_msg = b64encode(cipher_text)
    encrypted_text = b64encrypted_msg.decode("utf-8")
    return encrypted_text

# decrypt data
def decryptData(data: str, rsa_key: str):
    rawmsg = b64decode(data)
    key = RSA.import_key(rsa_key)

    cipher = Cipher_PKCS1_v1_5.new(key)
    b64decrypted_msg = cipher.decrypt(rawmsg, "")
    original_text = b64decrypted_msg.decode("utf-8")
    return original_text

# generate signature
def generateSignature(data: str, rsa_key: str):
    key = RSA.importKey(rsa_key)
    h = SHA256.new(data.replace('\n','\r\n').encode("utf-8"))
    signature = pkcs1_15.new(key).sign(h)
    bval = b64encode(signature).decode("utf-8")

    return bval

# validate signature
def validateSignature(data: str, signed_data: str, rsa_key: str):
    key = RSA.importKey(rsa_key)
    h = SHA256.new(data.replace('\n','\r\n').encode("utf-8"))
    signature = b64decode(signed_data)

    try:
        pkcs1_15.new(key).verify(h, signature)
        return True
    except (ValueError, TypeError):
        return False

plainText = """123456"""

encrypt = encryptData(plainText, public_key)
print("Encrypted: ", encrypt)
decrypt = decryptData(encrypt, private_key)
print("Decrypted: ", decrypt)
sign = generateSignature(plainText, private_key)
print("Signature: ", sign)
verified = validateSignature(plainText, sign, public_key)
print("Verification: ", verified)
Copy
Copied
<?php

$public_key = '-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM
K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce
z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD
lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF
FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO
GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP
AgMBAAE=
-----END PUBLIC KEY-----';

$private_key = '-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW
XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds
3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFDlONfqu1BDxhl4/2CZaaK6LwrLaKc
IxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyFFkNsoyX/Et0KldT0qWCsTexf3QON
PbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aOGaZLhGSrNufaQUCQOfWaBD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unjic2oCRp3zHISavKipBtQDVCAZwU
zz8hAoGBAJ1Jp28lt28cTwKQdYkK6iWt2lOLoPKZVbcoK/SI1LmV8J+Ox2jID1nc
2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv
BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz
-----END RSA PRIVATE KEY-----';

$plainText = '123456';

openssl_public_encrypt($plainText, $encrypted, $public_key);
$b64_enc = base64_encode($encrypted);
echo "Encrypted text : $b64_enc\n";

$b64_dec = base64_decode($b64_enc);
openssl_private_decrypt($b64_dec, $decrypted, $private_key);
echo "Decrypted text : $decrypted\n";

openssl_sign(str_replace('\n', '\r\n', $plainText), $encrypted, $private_key, OPENSSL_ALGO_SHA256);
$b64_enc = base64_encode($encrypted);
echo "Signature text : $b64_enc\n";

$b64_dec = base64_decode($b64_enc);
$verify_value = openssl_verify(str_replace('\n', '\r\n', $plainText), $b64_dec, $public_key, OPENSSL_ALGO_SHA256);
echo "Signature verify : $verify_value\n";
?>
Copy
Copied
const crypto = require("crypto");

var publicKey = "-----BEGIN PUBLIC KEY-----\n"+
"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM\n"+
"K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce\n"+
"z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD\n"+
"lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF\n"+
"FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO\n"+
"GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP\n"+
"AgMBAAE=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+W6qH7VU8vVhJYWmgYE+RvoK\n"+
"U5KadJHnEXpCkPU875IPfuVB9w7EnCsGAX/FAOGwGtW1cMbD4MocEGFuGi82+Wz0\n"+
"CBk/goJTaSDgfSjCfcBB8Mc028M8MZ3M6kgcIQKBgQCAoe89f/PeS7C1oMpbdNJl\n"+
"Wox+eV/4rpFhfyhVJhSbuPzc0kB49kf0gNjsIgwQgUOXSydnOVhTN/yQ1j0WfmAc\n"+
"PFTNFT9kav3STqyLijexBheNAPaQoltLdypYZdcpOJJiW5StLzkColRkpRhU3eOJ\n"+
"mNc5OKXvvFO0OmvTkTHf0wKBgGSeb4fvfFayqHzRiBGJxKlPTLYHF5pHHFlKQEUp\n"+
"5E7lTp/Xv95cDJG79ttE1zEVFGZiXor8nax5uu/EXxVKz6IUR3NlUgdjZ6kidwXF\n"+
"kjhEnHO/xnUACI77mcL9/BGBRsZFLUpr+1Unjic2oCRp3zHISavKipBtQDVCAZwU\n"+
"zz8hAoGBAJ1Jp28lt28cTwKQdYkK6iWt2lOLoPKZVbcoK/SI1LmV8J+Ox2jID1nc\n"+
"2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv\n"+
"BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz\n"+
"-----END RSA PRIVATE KEY-----";

function rsaencrypt(payload, key) {
    let encrypted = crypto.publicEncrypt(
      {
        key: key,
        padding: crypto.constants.RSA_PKCS1_PADDING,
        Hash: "sha256",
      },
      Buffer.from(payload)
    );

    return encrypted.toString("base64");
};

function rsadecrypt(payload, key) {
    let decrypted = crypto.privateDecrypt(
      {
        key: key,
        padding: crypto.constants.RSA_PKCS1_PADDING,
        Hash: "sha256",
      },
      Buffer.from(payload, 'base64')
    );

    return decrypted.toString();
};

function rsasign(payload, key) {
    let signature = crypto.sign("sha256", Buffer.from(payload.replaceAll('\n','\r\n')), {
      key: key,
      padding: crypto.constants.RSA_PKCS1_PADDING,
    });

    return signature.toString("base64");
};

function rsaverify(payload, key, signature) {
    let verification = crypto.verify(
      "sha256",
      Buffer.from(payload.replaceAll('\n','\r\n')),
      {
        key: key,
        padding: crypto.constants.RSA_PKCS1_PADDING,
      },
      Buffer.from(signature, 'base64')
    );

    return verification;
};

const plainText = "123456";
encryptedValue = rsaencrypt(plainText, publicKey);
console.log("Encrypted: " + encryptedValue);
decryptedValue = rsadecrypt(encryptedValue, privateKey);
console.log("Decrypted: " + decryptedValue);
signedValue = rsasign(plainText, privateKey);
console.log("Signed: " + signedValue);
console.log("Verified: " + rsaverify(plainText, publicKey, signedValue));
Copy
Copied
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.security.Signature;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


public class RSAEncryptDecryptSignVerify {
	private static final String RSA_ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";

    public static void main(String[] args) throws Exception {

        String publicKeyString = "-----BEGIN PUBLIC KEY-----\r\n"
        		+ "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM\r\n"
        		+ "K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce\r\n"
        		+ "z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD\r\n"
        		+ "lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF\r\n"
        		+ "FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO\r\n"
        		+ "GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP\r\n"
        		+ "AgMBAAE=\r\n"
        		+ "-----END PUBLIC KEY-----";
        String privateKeyString = "-----BEGIN RSA PRIVATE KEY-----\r\n"
        		+ "MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW\r\n"
        		+ "XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds\r\n"
        		+ "3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFDlONfqu1BDxhl4/2CZaaK6LwrLaKc\r\n"
        		+ "IxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyFFkNsoyX/Et0KldT0qWCsTexf3QON\r\n"
        		+ "PbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aOGaZLhGSrNufaQUCQOfWaBD4vcDcI\r\n"
        		+ "i+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnPAgMBAAECggEAEB4RP6Th6iJzT1DT\r\n"
        		+ "cNaX0tddtpaZrtKhs735XS5rcKlQ7BfSrUzR72pENWWXJ/S33ZAhcNEAqRqZt4QS\r\n"
        		+ "phpmq00KMAJTwb93NVad+nRXaSi6d9MhBda9ImnLfeVazzE3QBanzx7o2GKb/84u\r\n"
        		+ "YQJ3Ie4aZgb4SnAcBXM5WSsq3Ns1ETliO6goX45PK+kNEbSnsErFApp9YBIodZUG\r\n"
        		+ "CrSSmdkXYf4qKDevPZH/MySka1VCZtqlIJ9Xec9a2C7mecImK8bL4nk0CkUuZLWc\r\n"
        		+ "FNrmk//r0c3Jx8qINcXnz/+RqfNhmlSyZmK6FwN0sHkrNs6Jz7IanGpnTfYFq6jo\r\n"
        		+ "M3i5QQKBgQC32DR5rbStlBQguUKTklG2CHC74iJprK6ypFW1hw1yqcbUtiQYFqYm\r\n"
        		+ "IpaBy3HJVE5/W/3vvGDgTAOwcwoAvr7viesHFbmzBrqHc/oBWBkeUa4HLq/KGPRt\r\n"
        		+ "Azs8n/TUQdSSJZEkBn0CdVWNCSq2wqFfvedvmvf6yYDFTv3W4feH7wKBgQCVrPd0\r\n"
        		+ "Zi0XfJTdrTQNYAujojRcmPImSOR6LaVcrNFCAzpZ+W6qH7VU8vVhJYWmgYE+RvoK\r\n"
        		+ "U5KadJHnEXpCkPU875IPfuVB9w7EnCsGAX/FAOGwGtW1cMbD4MocEGFuGi82+Wz0\r\n"
        		+ "CBk/goJTaSDgfSjCfcBB8Mc028M8MZ3M6kgcIQKBgQCAoe89f/PeS7C1oMpbdNJl\r\n"
        		+ "Wox+eV/4rpFhfyhVJhSbuPzc0kB49kf0gNjsIgwQgUOXSydnOVhTN/yQ1j0WfmAc\r\n"
        		+ "PFTNFT9kav3STqyLijexBheNAPaQoltLdypYZdcpOJJiW5StLzkColRkpRhU3eOJ\r\n"
        		+ "mNc5OKXvvFO0OmvTkTHf0wKBgGSeb4fvfFayqHzRiBGJxKlPTLYHF5pHHFlKQEUp\r\n"
        		+ "5E7lTp/Xv95cDJG79ttE1zEVFGZiXor8nax5uu/EXxVKz6IUR3NlUgdjZ6kidwXF\r\n"
        		+ "kjhEnHO/xnUACI77mcL9/BGBRsZFLUpr+1Unjic2oCRp3zHISavKipBtQDVCAZwU\r\n"
        		+ "zz8hAoGBAJ1Jp28lt28cTwKQdYkK6iWt2lOLoPKZVbcoK/SI1LmV8J+Ox2jID1nc\r\n"
        		+ "2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv\r\n"
        		+ "BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz\r\n"
        		+ "-----END RSA PRIVATE KEY-----";
        
        String plainText = "123456";

        // Convert the key strings to public and private keys
        PublicKey publicKey = getPublicKey(publicKeyString);
        PrivateKey privateKey = getPrivateKey(privateKeyString);

        // Encrypt the plaintext
        String encrypted = encrypt(plainText, publicKey);
        System.out.println("Encrypted: " + new String(encrypted));

        // Decrypt the ciphertext
        String decrypted = decrypt(encrypted, privateKey);
        System.out.println("Decrypted: " + new String(decrypted));
        
        // Sign the plaintext
        String signed = sign(plainText, privateKey);
        System.out.println("Signed: " + new String(signed));

        // Verify the signature
        boolean verified = verify(plainText, signed, publicKey);
        System.out.println("Verified: " + verified);
    }

    public static String encrypt(String plaintext, PublicKey publicKey) throws Exception {
        Cipher encryptCipher = Cipher.getInstance(RSA_ECB_PKCS1_PADDING);
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] ciphertext = encryptCipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(ciphertext);
    }

    public static String decrypt(String ciphertext, PrivateKey privateKey) throws Exception {
        Cipher decryptCipher = Cipher.getInstance(RSA_ECB_PKCS1_PADDING);
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedText = decryptCipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedText, StandardCharsets.UTF_8);
    }

    public static String sign(String plaintext, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(plaintext.replace("\n", "\r\n").getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes = signature.sign();
        return Base64.getEncoder().encodeToString(signatureBytes);
    }

    public static boolean verify(String plaintext, String signature, PublicKey publicKey) throws Exception {
        Signature verifier = Signature.getInstance("SHA256withRSA");
        verifier.initVerify(publicKey);
        verifier.update(plaintext.replace("\n", "\r\n").getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes = Base64.getDecoder().decode(signature);
        return verifier.verify(signatureBytes);
    }

    public static PublicKey getPublicKey(String publicKeyString) throws Exception {
        String publicKeyPEM = publicKeyString
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\r\n", "")
                .replaceAll("\n", "");

        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
    }

    public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {  	
        String privateKeyPEM = privateKeyString
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replace("-----END RSA PRIVATE KEY-----", "")
                .replaceAll("\r\n", "")
                .replaceAll("\n", "");

        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPEM);
        
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
        return keyFactory.generatePrivate(keySpec);
    }
}
Copy
Copied
require "openssl"
require "base64"

public_key = "-----BEGIN PUBLIC KEY-----\n"+
  "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM\n"+
  "K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce\n"+
  "z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD\n"+
  "lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF\n"+
  "FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO\n"+
  "GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP\n"+
  "AgMBAAE=\n"+
  "-----END PUBLIC KEY-----"

private_key = "-----BEGIN RSA PRIVATE KEY-----\n"+
"MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW\n"+
"XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds\n"+
"3Ayjd1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NjsIgwQgUOXSydnOVhTN/yQ1j0WfmAc\n"+
"PFTNFT9kav3STqyLijexBheNAPaQoltLdypYZdcpOJJiW5StLzkColRkpRhU3eOJ\n"+
"mNc5OKXvvFO0OmvTkTHf0wKBgGSeb4fvfFayqHzRiBGJxKlPTLYHF5pHHFlKQEUp\n"+
"5E7lTp/Xv95cDJG79ttE1zEVFGZiXor8nax5uu/EXxVKz6IUR3NlUgdjZ6kidwXF\n"+
"kjhEnHO/xnUACI77mcL9/BGBRsZFLUpr+1Unjic2oCRp3zHISavKipBtQDVCAZwU\n"+
"zz8hAoGBAJ1Jp28lt28cTwKQdYkK6iWt2lOLoPKZVbcoK/SI1LmV8J+Ox2jID1nc\n"+
"2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv\n"+
"BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz\n"+
"-----END RSA PRIVATE KEY-----"

def rsaencrypt(payload, key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted = pkey.public_encrypt(payload, OpenSSL::PKey::RSA::PKCS1_PADDING)
  Base64.encode64(encrypted).encode('UTF-8')
end

def rsadecrypt(payload, key)
  pkey = OpenSSL::PKey::RSA.new(key)
  decrypted = pkey.private_decrypt(Base64.decode64(payload.encode('UTF-8')), OpenSSL::PKey::RSA::PKCS1_PADDING)
  decrypted.force_encoding('UTF-8')
end

def rsasign(payload, key)
  pkey = OpenSSL::PKey::RSA.new(key)
  signature = pkey.sign(OpenSSL::Digest::SHA256.new, payload.gsub("\n", "\r\n").encode('UTF-8'))
  Base64.encode64(signature).encode('UTF-8')
end

def rsaverify(payload, key, signature)
  begin
    pkey = OpenSSL::PKey::RSA.new(key)
    digest = OpenSSL::Digest::SHA256.new
    verified = pkey.verify(digest, Base64.decode64(signature), payload.gsub("\n", "\r\n"))

    return verified
  rescue OpenSSL::PKey::RSAError => e
    puts "Error: #{e.message}"
    return false
  end
end

plainText = "123456"
encryptedValue = rsaencrypt(plainText, public_key)
puts "Encrypted: #{encryptedValue}"
decryptedValue = rsadecrypt(encryptedValue, private_key)
puts "Decrypted: #{decryptedValue}"
signedValue = rsasign(plainText, private_key)
puts "Signed: #{signedValue}"
puts "Verified: #{rsaverify(plainText, public_key, signedValue)}"
Copy
Copied
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;public class RSAEncryptDecryptSignVerify
{
    string publicKeyString = "-----BEGIN PUBLIC KEY-----\r\n"
    + "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM\r\n"
    + "K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce\r\n"
    + "z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD\r\n"
    + "lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF\r\n"
    + "FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO\r\n"
    + "GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP\r\n"
    + "AgMBAAE=\r\n"
    + "-----END PUBLIC KEY-----";string privateKeyString = "-----BEGIN RSA PRIVATE KEY-----\r\n"
      + "MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW\r\n"
      + "XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds\r\n"
      + "3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFDlONfqu1BDxhl4/2CZaaK6LwrLaKc\r\n"
      + "IxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyFFkNsoyX/Et0KldT0qWCsTexf3QON\r\n"
      + "PbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aOGaZLhGSrNufaQUCQOfWaBD4vcDcI\r\n"
      + "i+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnPAgMBAAECggEAEB4RP6Th6iJzT1DT\r\n"
      + "cNaX0tddtpaZrtKhs735XS5rcKlQ7BfSrUzR72pENWWXJ/S33ZAhcNEAqRqZt4QS\r\n"
      + "phpmq00KMAJTwb93NVad+nRXaSi6d9MhBda9ImnLfeVazzE3QBanzx7o2GKb/84u\r\n"
      + "YQJ3Ie4aZgb4SnAcBXM5WSsq3Ns1ETliO6goX45PK+kNEbSnsErFApp9YBIodZUG\r\n"
      + "CrSSmdkXYf4qKDevPZH/MySka1VCZtqlIJ9Xec9a2C7mecImK8bL4nk0CkUuZLWc\r\n"
      + "FNrmk//r0c3Jx8qINcXnz/+RqfNhmlSyZmK6FwN0sHkrNs6Jz7IanGpnTfYFq6jo\r\n"
      + "M3i5QQKBgQC32DR5rbStlBQguUKTklG2CHC74iJprK6ypFW1hw1yqcbUtiQYFqYm\r\n"
      + "IpaBy3HJVE5/W/3vvGDgTAOwcwoAvr7viesHFbmzBrqHc/oBWBkeUa4HLq/KGPRt\r\n"
      + "Azs8n/TUQdSSJZEkBn0CdVWNCSq2wqFfvedvmvf6yYDFTv3W4feH7wKBgQCVrPd0\r\n"
      + "Zi0XfJTdrTQNYAujojRcmPImSOR6LaVcrNFCAzpZ+W6qH7VU8vVhJYWmgYE+RvoK\r\n"
      + "U5KadJHnEXpCkPU875IPfuVB9w7EnCsGAX/FAOGwGtW1cMbD4MocEGFuGi82+Wz0\r\n"
      + "CBk/goJTaSDgfSjCfcBB8Mc028M8MZ3M6kgcIQKBgQCAoe89f/PeS7C1oMpbdNJl\r\n"
      + "Wox+eV/4rpFhfyhVJhSbuPzc0kB49kf0gNjsIgwQgUOXSydnOVhTN/yQ1j0WfmAc\r\n"
      + "PFTNFT9kav3STqyLijexBheNAPaQoltLdypYZdcpOJJiW5StLzkColRkpRhU3eOJ\r\n"
      + "mNc5OKXvvFO0OmvTkTHf0wKBgGSeb4fvfFayqHzRiBGJxKlPTLYHF5pHHFlKQEUp\r\n"
      + "5E7lTp/Xv95cDJG79ttE1zEVFGZiXor8nax5uu/EXxVKz6IUR3NlUgdjZ6kidwXF\r\n"
      + "kjhEnHO/xnUACI77mcL9/BGBRsZFLUpr+1Unjic2oCRp3zHISavKipBtQDVCAZwU\r\n"
      + "zz8hAoGBAJ1Jp28lt28cTwKQdYkK6iWt2lOLoPKZVbcoK/SI1LmV8J+Ox2jID1nc\r\n"
      + "2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv\r\n"
      + "BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz\r\n"
      + "-----END RSA PRIVATE KEY-----";
    
    // string encryption
    public string EncryptString(string content, string publicKey)
    {
        RSACryptoServiceProvider rsaProvider = ImportPublicKey(publicKey);
        byte[] encryptedContent = rsaProvider.Encrypt(Encoding.ASCII.GetBytes(content), false);
        return Convert.ToBase64String(encryptedContent);
    }// string decryption
    public string DecryptString(string content, string privateKey)
    {
        byte[] bytContent = Convert.FromBase64String(content);
        RSACryptoServiceProvider rsaProvider = ImportPrivateKey(privateKey);
        byte[] decryptedContent = rsaProvider.Decrypt(bytContent, false);
        return Encoding.ASCII.GetString(decryptedContent);
    }
​
​
    // Creation and verification of digital signatures:
    public static byte[] GetDataHash(string sampleData, byte[] key)
    {
        SHA256Managed shaManaged = new SHA256Managed();
        byte[] hashHMAC = shaManaged.ComputeHash(Encoding.UTF8.GetBytes(sampleData));return hashHMAC;
    }public string GenerateDigitalSignature(string body, string privateKeyText)
    {
        var hash = GetDataHash(body.Replace("\n","\r\n"), Encoding.UTF8.GetBytes(privateKeyText));
        byte[] signedHash;using (RSACryptoServiceProvider rsa = ImportPrivateKey(privateKeyText))
        {
            signedHash = rsa.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }var encodedHash = Convert.ToBase64String(signedHash);
        return encodedHash;
    }public static RSACryptoServiceProvider ImportPublicKey(string pem)
    {
        var pr = new PemReader(new StringReader(pem));
        var publicKey = (AsymmetricKeyParameter)pr.ReadObject();
        var rsaParameters = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParameters);
        return csp;
    }public static RSACryptoServiceProvider ImportPrivateKey(string pem)
    {
        var pr = new PemReader(new StringReader(pem));AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
        RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParameters);
        return csp;
    }public bool VerifyDigitalSignature(string digitalSignature, string contents, string publicKeyText)
    {
        var hash = GetDataHash(contents.Replace("\n", "\r\n"), Encoding.UTF8.GetBytes(publicKeyText));bool verified;
        try
        {
            using (var publicKey = ImportPublicKey(publicKeyText))
            {
                verified = publicKey.VerifyHash(hash, Convert.FromBase64String(digitalSignature), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            }
        }
        catch
        {
            verified = false;
        }
        return verified;
    }public static void Main()
    {
        string value = "123456";
        string encryptedValue, decryptedValue, signedValue;
        bool validationResult;RSAEncryptDecryptSignVerify rsa = new RSAEncryptDecryptSignVerify();
        encryptedValue = rsa.EncryptString(value, rsa.publicKeyString);
        decryptedValue = rsa.DecryptString(encryptedValue, rsa.privateKeyString);
        signedValue = rsa.GenerateDigitalSignature(value, rsa.privateKeyString);
        validationResult = rsa.VerifyDigitalSignature(signedValue, value, rsa.publicKeyString);
​
        Console.WriteLine("Encrypted Value: " + encryptedValue);
        Console.WriteLine("Decrypted Value: " + decryptedValue);
        Console.WriteLine("Signature Value: " + signedValue);
        Console.WriteLine("Verification Value: " + validationResult);
    }
}
Copy
Copied
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
)

var publicKeyPEM = []byte(`-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBrfQ2DRdSS73F/KCnuzrQM
K6zlq8JZXK0J0AsgsB5nO4PTu7cWXUspjltt2bhL9eM/VD9770MH+nJQOwj9+Cce
z3RKn183mRKYVv3QSJLcVxqPX1ds3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFD
lONfqu1BDxhl4/2CZaaK6LwrLaKcIxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyF
FkNsoyX/Et0KldT0qWCsTexf3QONPbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aO
GaZLhGSrNufaQUCQOfWaBD4vcDcIi+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnP
AgMBAAE=
-----END PUBLIC KEY-----`)

var privateKeyPEM = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQBrfQ2DRdSS73F/KCnuzrQMK6zlq8JZXK0J0AsgsB5nO4PTu7cW
XUspjltt2bhL9eM/VD9770MH+nJQOwj9+Ccez3RKn183mRKYVv3QSJLcVxqPX1ds
3Ayjd1Xu4XX/bXNO57EqMdwwIKAeRozPEqFDlONfqu1BDxhl4/2CZaaK6LwrLaKc
IxsNB+Om5HveyxyuOcz+4jtcfS0S8Aq4ESyFFkNsoyX/Et0KldT0qWCsTexf3QON
PbNP79KJVFIgEsm26k9TccW/bUBWYJnlq9aOGaZLhGSrNufaQUCQOfWaBD4vcDcI
i+bjYbQAjehezzrODsIMrAgVhspK7rzk/qnPAgMBAAECggEAEB4RP6Th6iJzT1DT
cNaX0tddtpaZrtKhs735XS5r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1nc
2KXn0bGE0Hy4tCfvuO+kEOIydRCUJY0ca84fIfGYn9LCq3KThQqJLdkr8IPjqlkv
BVYHwKUyxTf1slDEqWzlTqZeFiJL5LFfsFyIMtvc9YBzvK4Swmbz
-----END RSA PRIVATE KEY-----`)

func rsaEncrypt(payload []byte, publicKey *rsa.PublicKey) ([]byte, error) {
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, payload)
	if err != nil {
		return nil, err
	}
	return encrypted, nil
}

func rsaDecrypt(encrypted []byte, privateKey *rsa.PrivateKey) ([]byte, error) {
	decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
	if err != nil {
		return nil, err
	}
	return decrypted, nil
}

func rsaSign(payload []byte, privateKey *rsa.PrivateKey) ([]byte, error) {
	hashed := sha256.Sum256(payload)
	signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed[:])
	if err != nil {
		return nil, err
	}
	return signature, nil
}

func rsaVerify(payload, signature []byte, publicKey *rsa.PublicKey) error {
	hashed := sha256.Sum256(payload)
	err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], signature)
	return err
}

func main() {
	plainText := []byte("654321")

	publicKeyBlock, _ := pem.Decode(publicKeyPEM)
	publicKey, _ := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes)

	privateKeyBlock, _ := pem.Decode(privateKeyPEM)
	privateKey, _ := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)

	encryptedValue, err := rsaEncrypt(plainText, publicKey.(*rsa.PublicKey))
	if err != nil {
		fmt.Println("Encryption error:", err)
		return
	}
	fmt.Println("Encrypted:", base64.StdEncoding.EncodeToString(encryptedValue))

	decryptedValue, err := rsaDecrypt(encryptedValue, privateKey)
	if err != nil {
		fmt.Println("Decryption error:", err)
		return
	}
	fmt.Println("Decrypted:", string(decryptedValue))

	signature, err := rsaSign(plainText, privateKey)
	if err != nil {
		fmt.Println("Signing error:", err)
		return
	}
	fmt.Println("Signed:", base64.StdEncoding.EncodeToString(signature))

	err = rsaVerify(plainText, signature, publicKey.(*rsa.PublicKey))
	if err != nil {
		fmt.Println("Verification failed:", err)
		return
	}
	fmt.Println("Verified: true")
}
Solaris is the brand name for the regulated entities Contis Financial Services Ltd and UAB „Finansinės paslaugos „Contis“, which are part of the Solaris Group.