Secret
'use strict';
const encode = text => new TextEncoder().encode(text);
const decode = data => new TextDecoder().decode(data);
const encrypt = async (password, text) => {
const ptUtf8 = encode(text);
const pwUtf8 = encode(password);
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
const iv = crypto.getRandomValues(new Uint8Array(12));
const alg = { name: 'AES-GCM', iv };
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, [ 'encrypt' ]);
const data = await crypto.subtle.encrypt(alg, key, ptUtf8);
return { data, iv };
};
const decrypt = async (password, { data, iv }) => {
const pwUtf8 = encode(password);
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
const alg = { name: 'AES-GCM', iv };
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, [ 'decrypt' ]);
const text = await crypto.subtle.decrypt(alg, key, data);
return decode(text);
};
return { encrypt, decrypt };
Vendors:
base64js,
rainbow
.