Skip to content
This repository has been archived by the owner on Jun 14, 2022. It is now read-only.

How to Encrypt and Decrypt a message

Haynar216 edited this page Mar 25, 2021 · 2 revisions

Overview

This page shows you how to use the receiver's public key to encrypt an "anonymous" message and decrypt that encrypted message with the private key corresponding to that public key.

Implementation

Two implementations are provided here, one uses a low-level cryptographic primitive McEliece, and the other uses a high-level construct js-nacl

js-nacl

Install

This library is registered on npmjs.org. To install it:

npm install js-nacl

Example Usage

const Base58 = require('base-58');
var nacl_factory = require("js-nacl");

nacl_factory.instantiate(function (nacl) {
    
    function encrypt(msg, public_key) {
        msg = nacl.encode_utf8(msg);
        public_key = Base58.decode(public_key);
        return Base58.encode(nacl.crypto_box_seal(msg, public_key));
    }
    
    function decrypt(encryptedMessage, public_key, private_key) {
        encryptedMessage = Base58.decode(encryptedMessage);
        public_key = Base58.decode(public_key);
        private_key = Base58.decode(private_key);
        return nacl.decode_utf8(nacl.crypto_box_seal_open(encryptedMessage, public_key, private_key));
    }
    
    /* Obtain your public and private keys through vsystems by a seed
    const vsys = require("@virtualeconomy/js-v-sdk");
    const constants = vsys.constants;
    let account = new vsys.Account(constants.TESTNET_BYTE);
    let seed = "pulp fantasy found coast ecology replace peasant age pattern choose advance enroll month recipe lion";
    account.buildFromSeed(seed, 0);
    let public_key = account.getPublicKey();
    let private_key = account.getPrivateKey();
    */
    
    let public_key = "W9gbhmRahbFu8zGj6F3vRwPGpd2pkDZu3iGdrZCGw6t";
    let private_key = "BGbLCzcKWKkmk7CHpXzFeRRepYRnZS4sxQabGp9Fmw9Q";
    let msg = "hello vsys system";
    let encryptedMessage = encrypt(msg, public_key);
    let decryptedMessage = decrypt(encryptedMessage, public_key, private_key);
    
    console.log(msg)
    console.log(encryptedMessage)
    console.log(decryptedMessage)
    
    /* output
    hello vsys system
    8y9MVK9dnxVFh67aBA5YmmVCWyGADinT8ha3R6h3yaHySQ9n6Zu6rBTcAcsbcSwUSUqWVJoe3D8SYpHYfs8JHUo5h
    hello vsys system
    */
});

McEliece

Install

npm install mceliece

Example Usage

(async () => {
	const keyPair /*: {privateKey: Uint8Array; publicKey: Uint8Array} */ =
		await mceliece.keyPair()
	;

	const plaintext /*: Uint8Array */ =
		new Uint8Array([104, 101, 108, 108, 111, 0]) // "hello"
	;

	const encrypted /*: Uint8Array */ =
		await mceliece.encrypt(plaintext, keyPair.publicKey)
	;

	const decrypted /*: Uint8Array */ =
		await mceliece.decrypt(encrypted, keyPair.privateKey) // same as plaintext
	;

	console.log(keyPair);
	console.log(plaintext);
	console.log(encrypted);
	console.log(decrypted);
})();