Encryption & Decryption
Introduction
This guide walks the user through how to programmatically perform encryption/decryption by using the eccrypto library.
Install the eccrypto library by running:
npm install eccrypto
Encryption
In this example, we will use an existing public key from a randomly generated public-private key pair to encrypt a simple text file containing "Hello BTFS". Later, we will decrypt this file.
The encrypt.js
program:
var eccrypto = require("eccrypto");
var fs = require('fs');
async function encrypt(inputFileName, encryptedFileName, publicKey){
try{
var encrypted = await eccrypto.encrypt(Buffer.from(publicKey, 'hex'), fs.readFileSync(inputFileName))
for (let key in encrypted) {
encrypted[key] = encrypted[key].toString('hex')}
fs.writeFileSync(encryptedFileName, JSON.stringify(encrypted));
}
catch(err){
console.log(err);
};
};
(async function(){
var myArgs = process.argv.slice(2);
if (myArgs.length != 3) {
console.log("Usage: node encrypt.js inputFileName encryptedFileName")
process.exit(1);
}
await encrypt(myArgs[0], myArgs[1], myArgs[2])
console.log(" ")
console.log("Successfully encrypted ", myArgs[0], " into ", myArgs[1], "using", myArgs[2])
})()
Run the program by inputting the Input File Name, Encrypted File Name, and the Public Key, where:
Input File Name = The file name in your current directory to be encrypted.
Encrypted File Name = Designate the name for the encrypted file.
Public Key = The public key used to encrypt the file.
Decryption
To decrypt the file we just encrypted, run the following program by inputting the Encrypted File Name, Decrypted File Name, and Private Key, where:
Encrypted File Name = The name of the encrypted file located in your current directory.
Decrypted File Name = Designate the name for the decrypted file.
Private Key = The private key associated with the public key used to encrypt the file.
var eccrypto = require("eccrypto");
var fs = require('fs');
async function decrypt(encryptedFileName, decryptedFileName, privateKey) {
try{
let encrypted = JSON.parse(fs.readFileSync(encryptedFileName, 'utf8'))
for (let key in encrypted) {
encrypted[key] = Buffer.from(encrypted[key],'hex')
}
let plaintext = await eccrypto.decrypt(Buffer.from(privateKey, 'hex'), encrypted)
fs.writeFileSync(decryptedFileName, plaintext);
}
catch(err){
console.log(err);
};
};
(async function () {
var myArgs = process.argv.slice(2);
// simple input sanity check
if (myArgs.length != 3) {
console.log("Usage: node decrpyt.js encryptedFileName decrptedFileName privateKey ")
process.exit(1);
}
await decrypt(myArgs[0], myArgs[1], myArgs[2])
console.log(" ")
console.log("Successfully decrypted ", myArgs[0], " into ", myArgs[1])
})()
The output:
Updated almost 3 years ago