-
Notifications
You must be signed in to change notification settings - Fork 10
/
aes4js.min.js
6 lines (6 loc) · 2.21 KB
/
aes4js.min.js
1
2
3
4
5
6
// aes4js, by dandavis. MIT applies.
(function(m,f){"function"===typeof define&&define.amd?define([],f):"object"===typeof exports?module.exports=f():m.aes4js=f()})(this,function(){function m(b){return crypto.subtle.digest("SHA-256",(new TextEncoder("utf-8")).encode(b)).then(function(a){return Array.from(new Uint8Array(a)).map(function(d){return("00"+d.toString(16)).slice(-2)}).join("")})}function f(b,a){if("object"===typeof b&&b.constructor===CryptoKey)return new Promise(function(d,c){return d(b)});10>b.length&&(b=b.repeat(12-b.length));
return m("349d"+b+"9d3458694307"+b.length+String(a)).then(function(d){var c=(new TextEncoder).encode(b),e=(new TextEncoder).encode(d);return window.crypto.subtle.importKey("raw",c,{name:"PBKDF2"},!1,["deriveBits","deriveKey"]).then(function(h){return window.crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:1E6+b.length,hash:"SHA-256"},h,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])})})}function n(b){var a=b.split(/[:;,]/);b=a[1];a=("base64"==a[2]?atob:decodeURIComponent)(a.pop());var d=
a.length,c=0,e=new Uint8Array(d);for(c;c<d;++c)e[c]=a.charCodeAt(c);return new Blob([e],{type:b})}return{encrypt:function(b,a){var d=window.crypto.getRandomValues(new Uint8Array(12)),c=(new TextEncoder("utf-8")).encode(a),e=0;"object"===typeof a&&(c=a,e=1);return f(b,d).then(function(h){return window.crypto.subtle.encrypt({name:"AES-GCM",iv:d,tagLength:128},h,c).then(function(k){return window.crypto.subtle.exportKey("jwk",h).then(function(g){return new Promise(function(p,q){var l=new FileReader;l.onload=
function(){p({encrypted:l.result,iv:[].slice.call(d),bin:e})};l.onerror=q;l.readAsDataURL(new Blob([k]))})})})})["catch"](console.error)},decrypt:function(b,a){"string"===typeof a&&(a=JSON.parse(a));return f(b,"number"===typeof a.bin?a.iv:"").then(function(d){return(new Promise(function(c,e){var h=n(a.encrypted),k=new FileReader;k.onload=function(){window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a.iv),tagLength:128},d,k.result).then(function(g){return a.bin?g:(new TextDecoder("utf-8")).decode(g)}).then(c)["catch"](function(g){"OperationError"===
String(g)&&(g="Oops!\n\nWrong Password, try again.");e(g)})};k.readAsArrayBuffer(h)}))["catch"](function(c){throw c;})})},derive:f}});