-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathcrypto.js
168 lines (148 loc) · 4.29 KB
/
crypto.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const UINT32_MAX = 0xffffffff;
const BUF_LEN = 1024;
const BUF_SIZE = BUF_LEN * Uint32Array.BYTES_PER_ELEMENT;
const randomPrefetcher = {
buf: crypto.randomBytes(BUF_SIZE),
pos: 0,
next() {
const { buf, pos } = this;
let start = pos;
if (start === buf.length) {
start = 0;
crypto.randomFillSync(buf);
}
const end = start + Uint32Array.BYTES_PER_ELEMENT;
this.pos = end;
return buf.slice(start, end);
},
};
const cryptoRandom = () => {
const buf = randomPrefetcher.next();
return buf.readUInt32LE(0) / (UINT32_MAX + 1);
};
const generateUUID = () => {
const h1 = randomPrefetcher.next().toString('hex');
const h2 = randomPrefetcher.next().toString('hex');
const buf = randomPrefetcher.next();
buf[0] = (buf[0] & 0x0f) | 0x40;
buf[2] = (buf[2] & 0x3f) | 0x80;
const h3 = buf.toString('hex');
const h4 = randomPrefetcher.next().toString('hex');
const d2 = h2.substring(0, 4);
const d3 = h3.substring(0, 4);
const d4 = h3.substring(4, 8);
const d5 = h2.substring(4, 8) + h4;
return [h1, d2, d3, d4, d5].join('-');
};
const generateKey = (length, possible) => {
const base = possible.length;
let key = '';
for (let i = 0; i < length; i++) {
const index = Math.floor(cryptoRandom() * base);
key += possible[index];
}
return key;
};
const CRC_LEN = 4;
const crcToken = (secret, key) => {
const md5 = crypto.createHash('md5').update(key + secret);
return md5.digest('hex').substring(0, CRC_LEN);
};
const generateToken = (secret, characters, length) => {
const key = generateKey(length - CRC_LEN, characters);
return key + crcToken(secret, key);
};
const validateToken = (secret, token) => {
if (!token) return false;
const len = token.length;
const crc = token.slice(len - CRC_LEN);
const key = token.slice(0, -CRC_LEN);
return crcToken(secret, key) === crc;
};
// Only change these if you know what you're doing
const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
const SCRYPT_PREFIX = '$scrypt$N=32768,r=8,p=1,maxmem=67108864$';
const serializeHash = (hash, salt) => {
const saltString = salt.toString('base64').split('=')[0];
const hashString = hash.toString('base64').split('=')[0];
return `${SCRYPT_PREFIX}${saltString}$${hashString}`;
};
const parseOptions = (options) => {
const values = [];
const items = options.split(',');
for (const item of items) {
const [key, val] = item.split('=');
values.push([key, Number(val)]);
}
return Object.fromEntries(values);
};
const deserializeHash = (phcString) => {
const [, name, options, salt64, hash64] = phcString.split('$');
if (name !== 'scrypt') {
throw new Error('Node.js crypto module only supports scrypt');
}
const params = parseOptions(options);
const salt = Buffer.from(salt64, 'base64');
const hash = Buffer.from(hash64, 'base64');
return { params, salt, hash };
};
const SALT_LEN = 32;
const KEY_LEN = 64;
const hashPassword = (password) =>
new Promise((resolve, reject) => {
crypto.randomBytes(SALT_LEN, (err, salt) => {
if (err) {
reject(err);
return;
}
crypto.scrypt(password, salt, KEY_LEN, SCRYPT_PARAMS, (err, hash) => {
if (err) {
reject(err);
return;
}
resolve(serializeHash(hash, salt));
});
});
});
let defaultHash;
hashPassword('').then((hash) => {
defaultHash = hash;
});
const validatePassword = (password, serHash = defaultHash) => {
const { params, salt, hash } = deserializeHash(serHash);
return new Promise((resolve, reject) => {
const callback = (err, hashedPassword) => {
if (err) {
reject(err);
return;
}
resolve(crypto.timingSafeEqual(hashedPassword, hash));
};
crypto.scrypt(password, salt, hash.length, params, callback);
});
};
const md5 = (filePath) => {
const hash = crypto.createHash('md5');
const file = fs.createReadStream(filePath);
return new Promise((resolve, reject) => {
file.on('error', reject);
hash.once('readable', () => {
resolve(hash.read().toString('hex'));
});
file.pipe(hash);
});
};
module.exports = {
cryptoRandom,
generateUUID,
generateKey,
crcToken,
generateToken,
validateToken,
hashPassword,
validatePassword,
md5,
};