Skip to content

Instantly share code, notes, and snippets.

@senid231
Forked from themikefuller/aes-gcm.js
Created September 25, 2020 11:20
Show Gist options
  • Save senid231/75f7d19746b3cbfb9554b1cdba47e768 to your computer and use it in GitHub Desktop.
Save senid231/75f7d19746b3cbfb9554b1cdba47e768 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment