Skip to content

Instantly share code, notes, and snippets.

@umanghome
Created July 27, 2021 07:13
Show Gist options
  • Save umanghome/83084a5003f7567b49ae095661a6406f to your computer and use it in GitHub Desktop.
Save umanghome/83084a5003f7567b49ae095661a6406f to your computer and use it in GitHub Desktop.
WebCrypto encrypt/decrypt
const ENCRYPT_PASSWORD = 'SEbSk7s9AxpUDiPgljlmYpRvr3yNVurYqmBm82swjhU';
let encryptionKey;
async function getEncryptionKey() {
if (encryptionKey) {
return encryptionKey;
}
const exported = {
alg: 'A256GCM',
ext: true,
k: ENCRYPT_PASSWORD,
key_ops: ['encrypt', 'decrypt'],
kty: 'oct',
};
encryptionKey = await crypto.subtle.importKey(
'jwk',
exported,
{ name: 'AES-GCM' },
exported.ext,
exported.key_ops
);
return encryptionKey;
}
async function encrypt(string) {
const encoded = new TextEncoder().encode(string);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ivString = iv.join('e');
const encrypted = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv,
},
await getEncryptionKey(),
encoded
);
const encryptedString = new Uint8Array(encrypted).join('e');
return `${encryptedString}.${ivString}`;
}
async function decrypt(string) {
const [cipherText, iv] = string.split('.');
const ivArray = new Uint8Array(iv.split('e').map(i => parseInt(i)));
const cipherTextArray = new Uint8Array(
cipherText.split('e').map(i => parseInt(i))
);
const buffer = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: ivArray,
},
await getEncryptionKey(),
cipherTextArray
);
return new TextDecoder().decoder(buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment