-
-
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
This file contains hidden or 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 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