1 | const bcrypt = require('bcryptjs');
|
2 | const shajs = require('sha.js');
|
3 |
|
4 | /**
|
5 | * Cryptography tools. Hashing, with salt (bcrypt) or without (sha)
|
6 | * @type {{SALT_ROUNDS: number, bcrypt: {hash: (function(*=): Promise), verifyHash: (function(*=, *=): Promise), getHashRounds: (function(*=): Promise)}, sha: {hash: (function(*=))}}}
|
7 | */
|
8 | const Crypto = {
|
9 |
|
10 | SALT_ROUNDS: 8,
|
11 |
|
12 | bcrypt: {
|
13 |
|
14 | /**
|
15 | * Hash txt with salt
|
16 | * @param {string} text
|
17 | * @return {Promise<string>} hash
|
18 | */
|
19 | async hash(text) {
|
20 | const salt = await bcrypt.genSalt(Crypto.SALT_ROUNDS);
|
21 | return bcrypt.hash(text, salt);
|
22 | },
|
23 |
|
24 | /**
|
25 | * Verify if text corresponds to hash
|
26 | * @param {string} text
|
27 | * @param {string} hash
|
28 | * @return {Promise<boolean>} valid
|
29 | */
|
30 | async verifyHash(text, hash) {
|
31 | return bcrypt.compare(text, hash);
|
32 | },
|
33 |
|
34 | /**
|
35 | * Detect if string is a hash and counts rounds if it is
|
36 | * @param {string} hash
|
37 | * @return {Promise.<number>} Number of rounds
|
38 | */
|
39 | async getHashRounds(hash) {
|
40 | return bcrypt.getRounds(hash);
|
41 | },
|
42 |
|
43 | },
|
44 |
|
45 | sha: {
|
46 |
|
47 | /**
|
48 | * Hash without salt
|
49 | *
|
50 | * @param {string} str
|
51 | * @return {string} hash
|
52 | */
|
53 | hash(str) {
|
54 | return shajs('sha256').update(str).digest('hex');
|
55 | },
|
56 |
|
57 | }
|
58 | // TODO sha
|
59 | };
|
60 |
|
61 | module.exports = Crypto; |
\ | No newline at end of file |