-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmac2.js
40 lines (34 loc) · 1.22 KB
/
hmac2.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
// note: encoded data is NOT encrypted
const crypto = require('crypto');
const secret = '20BBEBB8-DCC1-4544-AD32-7F3973CCED7A';
function createDigest(encodedData, format) {
return crypto
.createHmac('sha256', secret)
.update(encodedData)
.digest(format);
}
function encode(sourceData) {
const json = JSON.stringify(sourceData);
const encodedData = Buffer.from(json).toString('base64');
return `${encodedData}!${createDigest(encodedData, 'base64')}`;
}
function decode(value) {
let [encodedData, sourceDigest] = value.split('!');
if (!encodedData || !sourceDigest) throw new Error('invalid value(s)');
const json = Buffer.from(encodedData, 'base64').toString('utf8');
const decodedData = JSON.parse(json);
const checkDigest = createDigest(encodedData);
const digestsEqual = crypto.timingSafeEqual(
Buffer.from(sourceDigest, 'base64'),
checkDigest
);
if (!digestsEqual) throw new Error('invalid value(s)');
return decodedData;
}
const data = { name: 'brian' };
const encoded = encode(data);
const decoded = decode(encoded);
console.log('original data', data);
console.log('encoded as', encoded);
console.log('encoded size', Buffer.byteLength(encoded, 'utf8'));
console.log('decoded as', decoded);