Encrypt & Decrypt

Encryption

Each HandCash user-app relationship forms a unique keypair:

User 1 + App 1 = Keypair 1
User 1 + App 2 = Keypair 2


This can be used by the developer to encrypt data, without requiring any custody of the encryption key.

This feature requires the Decrypt & Encrypt permission. Otherwise you will receive an error.



User-to-App

User-to-App is an schema that allows both the user and the app to decrypt messages.


The below snippet shows how to encrypt a message between the user and the app:

const {HandCashConnect} = require('@handcash/handcash-connect');
const handCashConnect = new HandCashConnect('<app-id>'); 
const {PublicKey} = require('bsv');
const ECIES = require('bsv/ecies');

const cloudAccount = await handCashConnect.getAccountFromAuthToken(token);

const {publicKey} = await cloudAccount.profile.getEncryptionKeypair();
const ecPublicKey = PublicKey.fromString(publicKey);

const plainText = 'hello!';

const encryptedBuffer = ECIES().publicKey(ecPublicKey).encrypt(plainText);

console.log(encryptedBuffer.toString('base64'));

Output:

QklFMQPg/OQVAP3NgDAHicFFeXh5jGVVpBrCO811JgzH89c1NGhjPXQXg8hJnWolfhLZiKee91hqqXmazZC0luy3BaV4gL0r/o+yXfmU8583UfiYQA==

On the other hand, you may decrypt a message with the following:

const {HandCashCloudAccount} = require('@handcash/handcash-connect');
const {PrivateKey} = require('bsv');
const ECIES = require('bsv/ecies');

const cloudAccount = await handCashConnect.getAccountFromAuthToken(token);

const {privateKey} = await cloudAccount.profile.getEncryptionKeypair();
const ecPrivateKey = PrivateKey.fromWIF(privateKey);

const encryptedBuffer = Buffer.from('QklFMQPg/OQVAP3NgDAHicFFeXh5jGVVpBrCO811JgzH89c1NGhjPXQXg8hJnWolfhLZiKee91hqqXmazZC0luy3BaV4gL0r/o+yXfmU8583UfiYQA==', 'base64');
const decryptedBuffer = ECIES().privateKey(ecPrivateKey).decrypt(encryptedBuffer);

console.log(decryptedBuffer.toString('utf8'));

Output:

hello!