-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey.js
67 lines (50 loc) · 1.43 KB
/
key.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
60
61
62
63
64
65
66
67
/* eslint-disable no-console */
/** @module Key */
'use strict';
const crypto = require('crypto');
const errors = require('./errors');
const encoding = 'hex';
const emptyBuffer = Buffer.alloc(256);
const KEY_SIZE = 32;
class Key {
constructor(keyBuffer) {
// check thay the key size is KEY_SIZE
if (keyBuffer.length !== 16 && keyBuffer.length !== KEY_SIZE) {
throw errors.wrongKeyLength;
}
// Make sure the key is not empty
if (emptyBuffer.equals(keyBuffer)) {
throw errors.emptyKey;
}
this.buffer = keyBuffer;
}
/**
* Generates a new cryptographically secure random key
* @return {Promise<Key>} Returns a Key in case of success, an Error otherwise.
*/
static generate(keySize) {
return new Promise((resolve, reject) => {
// read keySize bits of random data
crypto.randomBytes(keySize, (err, buf) => {
// reject the promise in case of error
if (err) {
reject(err);
return;
}
// Debugging in case is needed
// console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
// console.log('=========');
// resolve successfully the promise in case of a valid key
resolve(new Key(buf));
});
});
}
/**
* Returns the key HEX encoded
* @return {string} HEX encoded string
*/
toString() {
return this.buffer.toString(encoding);
}
}
module.exports = Key;