forked from bcoin-org/bcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes.js
49 lines (41 loc) · 1.03 KB
/
aes.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
/*!
* aes.js - aes for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module crypto.aes
*/
const crypto = require('crypto');
const native = require('../native').binding;
/**
* Encrypt data with aes 256 cbc.
* @param {Buffer} data
* @param {Buffer} key
* @param {Buffer} iv
* @returns {Buffer}
*/
exports.encipher = function encipher(data, key, iv) {
const ctx = crypto.createCipheriv('aes-256-cbc', key, iv);
return Buffer.concat([ctx.update(data), ctx.final()]);
};
/**
* Decrypt data with aes 256 cbc.
* @param {Buffer} data
* @param {Buffer} key
* @param {Buffer} iv
* @returns {Buffer}
*/
exports.decipher = function decipher(data, key, iv) {
const ctx = crypto.createDecipheriv('aes-256-cbc', key, iv);
try {
return Buffer.concat([ctx.update(data), ctx.final()]);
} catch (e) {
throw new Error('Bad key for decryption.');
}
};
if (native) {
exports.encipher = native.encipher;
exports.decipher = native.decipher;
}