Last active
August 29, 2021 18:32
-
-
Save fawazahmed0/93bd56c2b44b0ce4596a64885c9c353f to your computer and use it in GitHub Desktop.
Encrypt and Decrypt file using web crypto api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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