index.jsView |
---|
6 | 6 | var mkdirp = require('mkdirp') |
7 | 7 | var path = require('path') |
8 | 8 | var curve = ecc.curves.k256 |
9 | 9 | var createHmac = require('hmac') |
| 10 | +var deepEqual = require('deep-equal') |
10 | 11 | |
| 12 | +function clone (obj) { |
| 13 | + var _obj = {} |
| 14 | + for(var k in obj) { |
| 15 | + if(Object.hasOwnProperty.call(obj, k)) |
| 16 | + _obj[k] = obj[k] |
| 17 | + } |
| 18 | + return _obj |
| 19 | +} |
11 | 20 | |
12 | 21 | function hash (data, enc) { |
13 | 22 | return new Blake2s().update(data, enc).digest('base64') + '.blake2s' |
14 | 23 | } |
170 | 179 | return createHmac(createHash, 64, key) |
171 | 180 | .update(data).digest('base64')+'.blake2s.hmac' |
172 | 181 | } |
173 | 182 | |
| 183 | +exports.signObj = function (keys, obj) { |
| 184 | + var _obj = clone(obj) |
| 185 | + var str = JSON.stringify(_obj, null, 2) |
| 186 | + var h = hash(str, 'utf8') |
| 187 | + _obj.signature = sign(keys, h) |
| 188 | + return _obj |
| 189 | +} |
| 190 | + |
| 191 | +exports.verifyObj = function (keys, obj) { |
| 192 | + obj = clone(obj) |
| 193 | + var sig = obj.signature |
| 194 | + delete obj.signature |
| 195 | + var str = JSON.stringify(obj, null, 2) |
| 196 | + var h = hash(str, 'utf8') |
| 197 | + return exports.verify(keys, sig, h) |
| 198 | +} |
| 199 | + |
| 200 | +exports.signObjHmac = function (secret, obj) { |
| 201 | + obj = clone(obj) |
| 202 | + var str = JSON.stringify(obj, null, 2) |
| 203 | + obj.hmac = exports.hmac(str, secret) |
| 204 | + return obj |
| 205 | +} |
| 206 | + |
| 207 | +exports.verifyObjHmac = function (secret, obj) { |
| 208 | + obj = clone(obj) |
| 209 | + var hmac = obj.hmac |
| 210 | + delete obj.hmac |
| 211 | + var str = JSON.stringify(obj, null, 2) |
| 212 | + var _hmac = exports.hmac(str, secret) |
| 213 | + return deepEqual(hmac, _hmac) |
| 214 | +} |