-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (47 loc) · 2.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Algorithm used => aes-256-cbc
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
// Initialize and generating Alice Diffier Hellman Keys
const alice = crypto.getDiffieHellman('modp15');
alice.generateKeys();
// Initialize and generating Bob Diffier Hellman Keys
const bob = crypto.getDiffieHellman('modp15');
bob.generateKeys();
// This is how to generate a shared secret key between Alice and Bob
// Public Key may come from server or a file
// In this example, it is coming from the above code
const aliceSecretKey = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecretKey = bob.computeSecret(alice.getPublicKey(), null, 'hex');
const encrypt = (text) => {
// Converting Alice Shared Secret Key to 32 bits
const key = crypto.scryptSync(aliceSecretKey, 'salt', 32);
// Initializing Initial Vector(IV) value to 16 bytes
const iv = crypto.randomBytes(16);
// Structuring message to be sent
const data = JSON.stringify({ text: text });
// Initiating Cipher Encryption and adding IV
let cipher = crypto.createCipheriv(algorithm, key, iv);
// Adding data to the cypher
let encrypted = cipher.update(data);
// Finalizing the cypher
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
};
const decrypt = (text) => {
// Converting Bob Shared Secret Key to 256 bits
const key = crypto.scryptSync(bobSecretKey, 'salt', 32);
// Creating buffer of iv and text string from encrypted text
const iv = Buffer.from(text.iv, 'hex');
let encryptedText = Buffer.from(text.encryptedData, 'hex');
// Initiating Decypher Decryption and adding IV
let decipher = crypto.createDecipheriv(algorithm, key, iv);
// Adding buffer encrypted string to the Decypher
let decrypted = decipher.update(encryptedText);
// Finalizing the Decypher
decrypted = Buffer.concat([decrypted, decipher.final()]);
return JSON.parse(decrypted);
};
const aliceSentEncryptedMessage = encrypt('Some serious stuff');
console.log(aliceSentEncryptedMessage);
const aliceDecryptedMessageByBob = decrypt(aliceSentEncryptedMessage);
console.log(aliceDecryptedMessageByBob);