Skip to content

Instantly share code, notes, and snippets.

@GramThanos
Created April 26, 2021 21:08
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 GramThanos/8a9d9d052899c725a1ea434db265d276 to your computer and use it in GitHub Desktop.
Save GramThanos/8a9d9d052899c725a1ea434db265d276 to your computer and use it in GitHub Desktop.
Simple AES string encrypt/decrypt
// Simple AES encryption and decryption
// The password should be of high complexity
// as it is just pashed through a SHA256 before
// it is used to encrypt/decrypt
async function encrypt(message, password) {
let iv = window.crypto.getRandomValues(new Uint8Array(12));
let alg = {name: "AES-GCM", iv: iv};
let pwHash = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(password));
let key = await window.crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
let cipher = await window.crypto.subtle.encrypt(
{name: "AES-GCM", iv: iv},
key,
new TextEncoder().encode(message)
);
let r = new Uint8Array(iv.byteLength + cipher.byteLength);
r.set(new Uint8Array(iv), 0);
r.set(new Uint8Array(cipher), iv.byteLength);
return r.buffer;
}
async function decrypt(cipher, password) {
cipher = new Uint8Array(cipher);
let iv = cipher.slice(0, 12).buffer;
let alg = {name: "AES-GCM", iv: iv};
let pwHash = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(password));
let key = await window.crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']);
try {
let message = await window.crypto.subtle.decrypt(
{name: "AES-GCM", iv: iv},
key,
cipher.slice(12, cipher.length).buffer
);
return new TextDecoder().decode(message);
} catch (e) {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment