-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
crypt.js
379 lines (330 loc) · 10.4 KB
/
crypt.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import HKDF from 'hkdf';
import srp from 'srp-js';
import forge from 'node-forge';
const DEFAULT_BYTE_LENGTH = 32;
const DEFAULT_PBKDF2_ITERATIONS = 1e5; // 100,000
/**
* Generate hex signing key used for AES encryption
*
* @param pass
* @param email
* @param salt
*/
export async function deriveKey(pass, email, salt) {
const combinedSalt = await _hkdfSalt(salt, email);
return _pbkdf2Passphrase(pass, combinedSalt);
}
/**
* Encrypt with RSA256 public key
*
* @param publicKeyJWK
* @param plaintext
* @return String
*/
export function encryptRSAWithJWK(publicKeyJWK, plaintext) {
if (publicKeyJWK.alg !== 'RSA-OAEP-256') {
throw new Error('Public key algorithm was not RSA-OAEP-256');
} else if (publicKeyJWK.kty !== 'RSA') {
throw new Error('Public key type was not RSA');
} else if (!publicKeyJWK.key_ops.find(o => o === 'encrypt')) {
throw new Error('Public key does not have "encrypt" op');
}
const encodedPlaintext = encodeURIComponent(plaintext);
const n = _b64UrlToBigInt(publicKeyJWK.n);
const e = _b64UrlToBigInt(publicKeyJWK.e);
const publicKey = forge.rsa.setPublicKey(n, e);
const encrypted = publicKey.encrypt(encodedPlaintext, 'RSA-OAEP', {
md: forge.md.sha256.create(),
});
return forge.util.bytesToHex(encrypted);
}
export function decryptRSAWithJWK(privateJWK, encryptedBlob) {
const n = _b64UrlToBigInt(privateJWK.n);
const e = _b64UrlToBigInt(privateJWK.e);
const d = _b64UrlToBigInt(privateJWK.d);
const p = _b64UrlToBigInt(privateJWK.p);
const q = _b64UrlToBigInt(privateJWK.q);
const dP = _b64UrlToBigInt(privateJWK.dp);
const dQ = _b64UrlToBigInt(privateJWK.dq);
const qInv = _b64UrlToBigInt(privateJWK.qi);
const privateKey = forge.rsa.setPrivateKey(n, e, d, p, q, dP, dQ, qInv);
const bytes = forge.util.hexToBytes(encryptedBlob);
const decrypted = privateKey.decrypt(bytes, 'RSA-OAEP', {
md: forge.md.sha256.create(),
});
return decodeURIComponent(decrypted);
}
/**
* Encrypt data using symmetric key
*
* @param jwkOrKey JWK or string representing symmetric key
* @param buff data to encrypt
* @param additionalData any additional public data to attach
* @returns {{iv, t, d, ad}}
*/
export function encryptAESBuffer(jwkOrKey, buff, additionalData = '') {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
const iv = forge.random.getBytesSync(12);
const cipher = forge.cipher.createCipher('AES-GCM', key);
cipher.start({ additionalData, iv, tagLength: 128 });
cipher.update(forge.util.createBuffer(buff));
cipher.finish();
return {
iv: forge.util.bytesToHex(iv),
t: forge.util.bytesToHex(cipher.mode.tag),
ad: forge.util.bytesToHex(additionalData),
d: forge.util.bytesToHex(cipher.output),
};
}
/**
* Encrypt data using symmetric key
*
* @param jwkOrKey JWK or string representing symmetric key
* @param plaintext string of data to encrypt
* @param additionalData any additional public data to attach
* @returns {{iv, t, d, ad}}
*/
export function encryptAES(jwkOrKey, plaintext, additionalData = '') {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
const iv = forge.random.getBytesSync(12);
const cipher = forge.cipher.createCipher('AES-GCM', key);
// Plaintext could contain weird unicode, so we have to encode that
const encodedPlaintext = encodeURIComponent(plaintext);
cipher.start({ additionalData, iv, tagLength: 128 });
cipher.update(forge.util.createBuffer(encodedPlaintext));
cipher.finish();
return {
iv: forge.util.bytesToHex(iv),
t: forge.util.bytesToHex(cipher.mode.tag),
ad: forge.util.bytesToHex(additionalData),
d: forge.util.bytesToHex(cipher.output),
};
}
/**
* Decrypt AES using a key
*
* @param jwkOrKey JWK or string representing symmetric key
* @param encryptedResult encryption data
* @returns String
*/
export function decryptAES(jwkOrKey, encryptedResult) {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
// ~~~~~~~~~~~~~~~~~~~~ //
// Decrypt with AES-GCM //
// ~~~~~~~~~~~~~~~~~~~~ //
const decipher = forge.cipher.createDecipher('AES-GCM', key);
decipher.start({
iv: forge.util.hexToBytes(encryptedResult.iv),
tagLength: encryptedResult.t.length * 4,
tag: forge.util.hexToBytes(encryptedResult.t),
additionalData: forge.util.hexToBytes(encryptedResult.ad),
});
decipher.update(forge.util.createBuffer(forge.util.hexToBytes(encryptedResult.d)));
if (decipher.finish()) {
return decodeURIComponent(decipher.output.toString());
} else {
throw new Error('Failed to decrypt data');
}
}
/**
* Decrypts AES using a key to buffer
* @param jwkOrKey
* @param encryptedResult
* @returns {string}
*/
export function decryptAESToBuffer(jwkOrKey, encryptedResult) {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
// ~~~~~~~~~~~~~~~~~~~~ //
// Decrypt with AES-GCM //
// ~~~~~~~~~~~~~~~~~~~~ //
const decipher = forge.cipher.createDecipher('AES-GCM', key);
decipher.start({
iv: forge.util.hexToBytes(encryptedResult.iv),
tagLength: encryptedResult.t.length * 4,
tag: forge.util.hexToBytes(encryptedResult.t),
additionalData: forge.util.hexToBytes(encryptedResult.ad),
});
decipher.update(forge.util.createBuffer(forge.util.hexToBytes(encryptedResult.d)));
if (decipher.finish()) {
return Buffer.from(forge.util.bytesToHex(decipher.output), 'hex');
} else {
throw new Error('Failed to decrypt data');
}
}
/**
* Generate a random key
*
* @returns {Promise}
*/
export function srpGenKey() {
return new Promise((resolve, reject) => {
srp.genKey((err, secret1Buffer) => {
if (err) {
reject(err);
} else {
resolve(secret1Buffer.toString('hex'));
}
});
});
}
/**
* Generate a random AES256 key for use with symmetric encryption
*/
export async function generateAES256Key() {
const c = window.crypto;
const subtle = c ? c.subtle || c.webkitSubtle : null;
if (subtle) {
console.log('[crypt] Using Native AES Key Generation');
const key = await subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, [
'encrypt',
'decrypt',
]);
return subtle.exportKey('jwk', key);
} else {
console.log('[crypt] Using Fallback Forge AES Key Generation');
const key = forge.util.bytesToHex(forge.random.getBytesSync(32));
return {
kty: 'oct',
alg: 'A256GCM',
ext: true,
key_ops: ['encrypt', 'decrypt'],
k: _hexToB64Url(key),
};
}
}
/**
* Generate RSA keypair JWK with 2048 bits and exponent 0x10001
*
* @returns Object
*/
export async function generateKeyPairJWK() {
// NOTE: Safari has crypto.webkitSubtle, but it does not support RSA-OAEP-SHA256
const subtle = window.crypto && window.crypto.subtle;
if (subtle) {
console.log('[crypt] Using Native RSA Generation');
const pair = await subtle.generateKey(
{
name: 'RSA-OAEP',
publicExponent: new Uint8Array([1, 0, 1]),
modulusLength: 2048,
hash: 'SHA-256',
},
true,
['encrypt', 'decrypt'],
);
return {
publicKey: await subtle.exportKey('jwk', pair.publicKey),
privateKey: await subtle.exportKey('jwk', pair.privateKey),
};
} else {
console.log('[crypt] Using Forge RSA Generation');
const pair = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
const privateKey = {
alg: 'RSA-OAEP-256',
kty: 'RSA',
key_ops: ['decrypt'],
ext: true,
d: _bigIntToB64Url(pair.privateKey.d),
dp: _bigIntToB64Url(pair.privateKey.dP),
dq: _bigIntToB64Url(pair.privateKey.dQ),
e: _bigIntToB64Url(pair.privateKey.e),
n: _bigIntToB64Url(pair.privateKey.n),
p: _bigIntToB64Url(pair.privateKey.p),
q: _bigIntToB64Url(pair.privateKey.q),
qi: _bigIntToB64Url(pair.privateKey.qInv),
};
const publicKey = {
alg: 'RSA-OAEP-256',
kty: 'RSA',
key_ops: ['encrypt'],
e: _bigIntToB64Url(pair.publicKey.e),
n: _bigIntToB64Url(pair.publicKey.n),
};
return { privateKey, publicKey };
}
}
// ~~~~~~~~~~~~~~~~ //
// Helper Functions //
// ~~~~~~~~~~~~~~~~ //
/**
* Combine email and raw salt into usable salt
*
* @param rawSalt
* @param rawEmail
* @returns {Promise}
*/
async function _hkdfSalt(rawSalt, rawEmail) {
return new Promise(resolve => {
const hkdf = new HKDF('sha256', rawSalt, rawEmail);
hkdf.derive('', DEFAULT_BYTE_LENGTH, buffer => resolve(buffer.toString('hex')));
});
}
/**
* Convert a JSBN BigInteger to a URL-safe version of base64 encoding. This
* should only be used for encoding JWKs
*
* @param n BigInteger
* @returns {string}
*/
function _bigIntToB64Url(n) {
return _hexToB64Url(n.toString(16));
}
function _hexToB64Url(h) {
const bytes = forge.util.hexToBytes(h);
return window
.btoa(bytes)
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function _b64UrlToBigInt(s) {
return new forge.jsbn.BigInteger(_b64UrlToHex(s), 16);
}
function _b64UrlToHex(s) {
const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
return forge.util.bytesToHex(window.atob(b64));
}
/**
* Derive key from password
*
* @param passphrase
* @param salt hex representation of salt
*/
async function _pbkdf2Passphrase(passphrase, salt) {
if (window.crypto && window.crypto.subtle) {
console.log('[crypt] Using native PBKDF2');
const k = await window.crypto.subtle.importKey(
'raw',
Buffer.from(passphrase, 'utf8'),
{ name: 'PBKDF2' },
false,
['deriveBits'],
);
const algo = {
name: 'PBKDF2',
salt: Buffer.from(salt, 'hex'),
iterations: DEFAULT_PBKDF2_ITERATIONS,
hash: 'SHA-256',
};
const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8);
return Buffer.from(derivedKeyRaw).toString('hex');
} else {
console.log('[crypt] Using Forge PBKDF2');
const derivedKeyRaw = forge.pkcs5.pbkdf2(
passphrase,
forge.util.hexToBytes(salt),
DEFAULT_PBKDF2_ITERATIONS,
DEFAULT_BYTE_LENGTH,
forge.md.sha256.create(),
);
return forge.util.bytesToHex(derivedKeyRaw);
}
}