gun/sea/decrypt.js
sirpy 29ed57e955
react native support (#5)
* WIP: use isomorphic-webcrypto for RN

* WIP: expo friendly exports

* WIP: buffer for RN

* WIP: textencoder for RN

* WIP: aeskey from jwk instead of raw for RN

* fix: missing taglength for msrcrypto

* add: update isomorphic-webcrypto

* add: match isocrypto api

* add: failing test for 4e2 as 400

* fix: remove extra atob btoa

* add: sea unbuild

* refactor: according to mhelander review

* refactor: shorter require

* fix: make bug test pass, capitlize bug test.

* fix: npm ci + sea test

* add: restore old browser export and add react-native friendly exports

* fix: import buffer into correct global/window

* fix: bad comparison

* fix: only include buffer if no btoa/atob
2019-12-08 17:41:26 +02:00

41 lines
1.4 KiB
JavaScript

var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var aeskey = require('./aeskey');
SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
opt = opt || {};
var key = (pair||opt).epriv || pair;
if(!key){
pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
key = pair.epriv || pair;
}
var json = S.parse(data);
var buf, bufiv, bufct; try{
buf = shim.Buffer.from(json.s, opt.encode || 'base64');
bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
}, aes, new Uint8Array(bufct)));
}catch(e){
if('utf8' === opt.encode){ throw "Could not decrypt" }
if(SEA.opt.fallback){
opt.encode = 'utf8';
return await SEA.decrypt(data, pair, cb, opt);
}
}
var r = S.parse(new shim.TextDecoder('utf8').decode(ct));
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.decrypt;