-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.js
59 lines (53 loc) · 1.67 KB
/
encryption.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
58
59
const bip39 = require("bip39");
const { hdkey } = require("ethereumjs-wallet");
const { createCipheriv, createDecipheriv } = require("crypto");
const encodeSecret = (mnemonic, id, secret, encoding) => {
const wallet = hdkey
.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic))
.derivePath(`m/44'/60'/0'/0/0`)
.getWallet();
const privateKey = wallet.privateKey;
const key = privateKey.slice(0, 24);
// const aad = Buffer.from('0123456789', 'hex');
const nonce = Buffer.alloc(12);
const dataView = new DataView(nonce.buffer);
dataView.setUint32(0, id);
const cipher = createCipheriv("aes-192-ccm", key, nonce, {
authTagLength: 16,
});
/* cipher.setAAD(aad, {
plaintextLength: Buffer.byteLength(secret)
}); */
const ciphertext = cipher.update(secret, encoding);
cipher.final();
const tag = cipher.getAuthTag();
return {
ciphertext,
tag,
};
};
const decodeSecret = (mnemonic, id, { ciphertext, tag }, encoding) => {
const wallet = hdkey
.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic))
.derivePath(`m/44'/60'/0'/0/0`)
.getWallet();
const privateKey = wallet.privateKey;
const key = privateKey.slice(0, 24);
// const aad = Buffer.from('0123456789', 'hex');
const nonce = Buffer.alloc(12);
const dataView = new DataView(nonce.buffer);
dataView.setUint32(0, id);
const decipher = createDecipheriv("aes-192-ccm", key, nonce, {
authTagLength: 16,
});
decipher.setAuthTag(tag);
/* decipher.setAAD(aad, {
plaintextLength: ciphertext.length
}); */
const receivedPlaintext = decipher.update(ciphertext, null, encoding);
return receivedPlaintext;
};
module.exports = {
encodeSecret,
decodeSecret,
};