Skip to content

Instantly share code, notes, and snippets.

@syst3mw0rm
Created October 25, 2018 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syst3mw0rm/9b22a1eadd6cbf38474573d54cd54f0c to your computer and use it in GitHub Desktop.
Save syst3mw0rm/9b22a1eadd6cbf38474573d54cd54f0c to your computer and use it in GitHub Desktop.
// helper methods starts
var lc = ["0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "a", "b", "c", "d", "e", "f"];
var uc = ["0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F"];
function toHex(val, uppercase) {
var set = uppercase ? uc : lc;
return set[Math.floor(val / 16)] + set[val % 16];
}
function toArrayBuffer(str) {
str = str.toLowerCase().replace(/\s/g, "");
if (str.length % 2 == 1)
str = "0" + str;
var len = Math.floor(str.length / 2);
var buffer = new Uint8Array(len);
var curr = -1;
for (var i = 0; i < str.length; ++i) {
var c = str[i];
var val = lc.indexOf(c);
if (val == -1)
throw Error("unexpected character")
if (curr === -1) {
curr = 16 * val;
} else {
buffer[Math.floor(i / 2)] = curr + val;
curr = -1;
}
}
return buffer;
}
function toString(arr, opts) {
var defaultOpts = {
grouping: 0,
rowlength: 0,
uppercase: true,
};
if (opts == undefined)
opts = {}
opts = defaultOpts;
var str = "";
var group = 0, column = 0;
for (var i = 0; i < arr.length; ++i) {
str += toHex(arr[i], opts.uppercase);
if (i === arr.length - 1)
break;
if (opts.grouping > 0 && ++group === opts.grouping) {
group = 0;
if (opts.rowlength > 0 && ++column === opts.rowlength) {
column = 0;
str += "\n";
}
else
str += " ";
}
}
return str;
}
const ab2str = buf => String.fromCharCode.apply(null, new Uint16Array(buf));
const ab2hex = ab => toString(new Uint8Array(ab));
// helper method ends
async function importCryptoKey(key){
return await window.crypto.subtle.importKey(
"raw", // can be "jwk" or "raw"
toArrayBuffer(key).buffer,
{name: 'AES-GCM'},
true, // whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] // can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
)
};
async function decrypt_a({ text, iv, key }){
const arrayBuffer = await window.crypto.subtle.decrypt({
name: 'AES-GCM',
iv: toArrayBuffer(iv).buffer
},
await importCryptoKey(key),
toArrayBuffer(text).buffer,
);
return ab2hex(arrayBuffer);
};
key = 'E52BC6CEDC2E096584B1F57D3AE6A60724C7B301EECB975813819673E6D23126';
iv = 'B5DDEDB80480A649D1763BE7';
encrypted_data = '37631B44E6B7DB7C404F2947F40FC629BB537BF303B728A674280C23528C3B09815BA2CD39B3844A38C4527464353A66';
res = await decrypt_a({text: encrypted_data, iv, key});
console.log(res);
@syst3mw0rm
Copy link
Author

returns EEE72939E910F74104846B5BADBDDAD007A46E3392ADE713F6EE33900299C250

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment