try/catch WebCrypto to forge

This commit is contained in:
AJ ONeal 2015-10-23 03:19:41 -07:00
förälder d02fd1bbf3
incheckning 8841322eff

Visa fil

@ -12,8 +12,19 @@ exports.sha1Hmac = function (key, bytes) {
var Unibabel = window.Unibabel;
if (window.crypto) {
return window.crypto.subtle.importKey(
function useForge() {
var forge = window.forge;
var hmac = forge.hmac.create();
var digest;
hmac.start('sha1', Unibabel.bufferToBinaryString(key));
hmac.update(Unibabel.bufferToBinaryString(bytes));
digest = hmac.digest().toHex();
return window.Promise.resolve(digest);
}
function useWebCrypto() {
return (window.crypto.subtle||window.crypto.webkitSubtle).importKey(
"raw"
, key
, { name: "HMAC"
@ -40,10 +51,10 @@ exports.sha1Hmac = function (key, bytes) {
["sign", "verify"] //can be any combination of "sign" and "verify"
)
*/
.then(function (key) {
return window.crypto.subtle.sign(
.then(function (cryptoKey) {
return (window.crypto.subtle||window.crypto.webkitSubtle).sign(
{ name: "HMAC" }
, key // from generateKey or importKey above
, cryptoKey // from generateKey or importKey above
, new Uint8Array(bytes) // ArrayBuffer of data you want to sign
)
.then(function(signature){
@ -52,15 +63,29 @@ exports.sha1Hmac = function (key, bytes) {
});
});
}
else if (window.forge) {
var forge = window.forge;
var hmac = forge.hmac.create();
var digest;
hmac.start('sha1', Unibabel.bufferToBinaryString(key));
hmac.update(Unibabel.bufferToBinaryString(bytes));
digest = hmac.digest().toHex();
return window.Promise.resolve(digest);
if (window.crypto) {
// WebCrypto is so unreliable right now... ugh...
try {
return useWebCrypto().then(function (result) {
return result;
}, function (err) {
console.warn(err);
console.warn(err.stack);
console.warn("WebCrypto failed, trying forge.js");
return useForge();
});
} catch(e) {
console.warn(e);
console.warn(e.stack);
console.warn("WebCrypto threw exception, trying forge.js");
return useForge();
}
}
else if (window.forge) {
return useForge();
}
else {
throw new Error("WebCrypto or forge.js is required to create a sha1 hmac");