Skip to content

Instantly share code, notes, and snippets.

@fawazahmed0
Last active August 29, 2021 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fawazahmed0/93bd56c2b44b0ce4596a64885c9c353f to your computer and use it in GitHub Desktop.
Save fawazahmed0/93bd56c2b44b0ce4596a64885c9c353f to your computer and use it in GitHub Desktop.
Encrypt and Decrypt file using web crypto api
async function encryptblob(blob) {
let iv = crypto.getRandomValues(new Uint8Array(12));
let algorithm = {
name: "AES-GCM",
iv: iv
}
let key = await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
let data = await blob.arrayBuffer();
const result = await crypto.subtle.encrypt(algorithm, key, data);
let exportedkey = await crypto.subtle.exportKey("jwk", key)
return [new Blob([result]), iv.toString(), exportedkey]
}
async function decryptblob(encblob, ivdata, exportedkey) {
let key = await crypto.subtle.importKey(
"jwk",
exportedkey,
{ name: "AES-GCM" },
true,
["encrypt", "decrypt"]
);
let iv = new Uint8Array(ivdata.split(','))
let algorithm = {
name: "AES-GCM",
iv: iv
}
let data = await encblob.arrayBuffer();
let decryptedData = await crypto.subtle.decrypt(algorithm, key, data);
return new Blob([decryptedData])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment