-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwork.js
42 lines (38 loc) · 1.62 KB
/
work.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
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var sha = require('./sha256');
var u;
SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
opt = opt || {};
if(salt instanceof Function){
cb = salt;
salt = u;
}
data = (typeof data == 'string')? data : await shim.stringify(data);
if('sha' === (opt.name||'').toLowerCase().slice(0,3)){
var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64')
if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }
return rsha;
}
salt = salt || shim.random(9);
var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);
var work = await (shim.ossl || shim.subtle).deriveBits({
name: opt.name || 'PBKDF2',
iterations: opt.iterations || S.pbkdf2.iter,
salt: new shim.TextEncoder().encode(opt.salt || salt),
hash: opt.hash || S.pbkdf2.hash,
}, key, opt.length || (S.pbkdf2.ks * 8))
data = shim.random(data.length) // Erase data in case of passphrase
var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64')
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.work;