Skip to content

Instantly share code, notes, and snippets.

@themikefuller
Created October 15, 2018 02:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save themikefuller/aca9491f960cbb8d94cdd7236698f0cd to your computer and use it in GitHub Desktop.
Save themikefuller/aca9491f960cbb8d94cdd7236698f0cd to your computer and use it in GitHub Desktop.
AES-GCM Encryption and Decryption Examples using Web Crypto (subtle.crypto) JavaScript API
async function generateKey() {
return await crypto.subtle.generateKey({
"name":"AES-GCM",
"length":256
},true,['encrypt','decrypt']);
}
async function exportKey(key) {
return await crypto.subtle.exportKey('jwk', key);
}
async function importKey(jwk) {
return await crypto.subtle.importKey('jwk', jwk, {
"name":"AES-GCM"
}, false, ['encrypt','decrypt']);
}
async function encrypt(string,key) {
let encoded = new TextEncoder().encode(string);
let iv = crypto.getRandomValues(new Uint8Array(12));
let encrypted = await crypto.subtle.encrypt({"name":"AES-GCM","iv":iv}, key, encoded);
return encrypted = {"encrypted":encrypted, "iv": iv};
}
async function decrypt(encrypted,iv, key) {
let decrypted = await crypto.subtle.decrypt({"name":"AES-GCM","iv":iv}, key, encrypted);
let decoded = new TextDecoder().decode(decrypted);
return decoded;
}
@AJLoveChina
Copy link

This is good sample, but AES-GCM crypto is not supported in Edge/IE11, do you know how to AES-GCM in Edge/IE11? Is there pure javascript code that doesn't rely on native crypto api ?

@yonixw
Copy link

yonixw commented Nov 28, 2021

This is good sample, but AES-GCM crypto is not supported in Edge/IE11, do you know how to AES-GCM in Edge/IE11? Is there pure javascript code that doesn't rely on native crypto api ?

Maybe this can help:
https://stackoverflow.com/questions/41449185/how-to-decrypt-data-from-the-result-of-an-ie-11-encrypt-operation-using-aes-gcm

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