Skip to content

Instantly share code, notes, and snippets.

@korrio
Last active March 24, 2023 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korrio/80c0f610af30327f17005c1b09536a9d to your computer and use it in GitHub Desktop.
Save korrio/80c0f610af30327f17005c1b09536a9d to your computer and use it in GitHub Desktop.
Encrypt / decrypt CSV file in Diffie-Hellman algorithm ?
// Import required libraries
const crypto = require('crypto');
const fs = require('fs');
// Generate a random large prime number (p) and a primitive root (g)
const p = crypto.createDiffieHellman(256).getPrime();
const g = 2;
// Alice's secret key (a), alice is PTG as a data supplier
const a = crypto.randomBytes(32);
// Bob's secret key (b), bob is SB as a data broker
const b = crypto.randomBytes(32);
// Calculate A = g^a mod p
const dhAlice = crypto.createDiffieHellman(a);
const A = dhAlice.generateKeys();
const publicKeyAlice = dhAlice.getPublicKey();
// Calculate B = g^b mod p
const dhBob = crypto.createDiffieHellman(b);
const B = dhBob.generateKeys();
const publicKeyBob = dhBob.getPublicKey();
// Alice and Bob exchange public keys over a public channel
// Alice sends publicKeyAlice to Bob, and Bob sends publicKeyBob to Alice
// Alice generates the shared secret key (s) using Bob's public key
const sAlice = dhAlice.computeSecret(publicKeyBob);
// Bob generates the shared secret key (s) using Alice's public key
const sBob = dhBob.computeSecret(publicKeyAlice);
// Verify that the shared secret keys are the same
console.log(sAlice.equals(sBob)); // true
// Use the shared secret key to encrypt and decrypt a file using AES encryption
const inputFile = 'example.csv';
const outputFile = 'example-encrypted.csv';
// Read the input file
const input = fs.readFileSync(inputFile);
// Generate a random initialization vector (IV)
const iv = crypto.randomBytes(16);
// Create a cipher using AES-256-CBC encryption with the shared secret key and IV
const cipher = crypto.createCipheriv('aes-256-cbc', sAlice, iv);
// Encrypt the input data and write it to the output file
const encrypted = Buffer.concat([iv, cipher.update(input), cipher.final()]);
fs.writeFileSync(outputFile, encrypted);
// Read the encrypted data from the output file
const encryptedData = fs.readFileSync(outputFile);
// Extract the IV from the encrypted data
const ivExtracted = encryptedData.slice(0, 16);
// Create a decipher using AES-256-CBC decryption with the shared secret key and IV
const decipher = crypto.createDecipheriv('aes-256-cbc', sBob, ivExtracted);
// Decrypt the encrypted data and write it to the output file
const decrypted = Buffer.concat([decipher.update(encryptedData.slice(16)), decipher.final()]);
fs.writeFileSync('example-decrypted.csv', decrypted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment