-
Notifications
You must be signed in to change notification settings - Fork 305
/
encryption-helper.js
63 lines (49 loc) · 1.6 KB
/
encryption-helper.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
'use strict';
const crypto = require('crypto');
const ece = require('http_ece');
const urlBase64 = require('urlsafe-base64');
const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
if (!userPublicKey) {
throw new Error('No user public key provided for encryption.');
}
if (typeof userPublicKey !== 'string') {
throw new Error('The subscription p256dh value must be a string.');
}
if (urlBase64.decode(userPublicKey).length !== 65) {
throw new Error('The subscription p256dh value should be 65 bytes long.');
}
if (!userAuth) {
throw new Error('No user auth provided for encryption.');
}
if (typeof userAuth !== 'string') {
throw new Error('The subscription auth key must be a string.');
}
if (urlBase64.decode(userAuth).length < 16) {
throw new Error('The subscription auth key should be at least 16 ' +
'bytes long');
}
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
throw new Error('Payload must be either a string or a Node Buffer.');
}
if (typeof payload === 'string' || payload instanceof String) {
payload = new Buffer(payload);
}
const localCurve = crypto.createECDH('prime256v1');
const localPublicKey = localCurve.generateKeys();
const salt = urlBase64.encode(crypto.randomBytes(16));
const cipherText = ece.encrypt(payload, {
version: contentEncoding,
dh: userPublicKey,
privateKey: localCurve,
salt: salt,
authSecret: userAuth
});
return {
localPublicKey: localPublicKey,
salt: salt,
cipherText: cipherText
};
};
module.exports = {
encrypt: encrypt
};