Skip to content

Instantly share code, notes, and snippets.

@Slyke
Created August 9, 2023 22:02
Show Gist options
  • Save Slyke/bcd4cdf09a683772ca99ce87571d1b63 to your computer and use it in GitHub Desktop.
Save Slyke/bcd4cdf09a683772ca99ce87571d1b63 to your computer and use it in GitHub Desktop.
Encrypt and decrypt text
async function deriveKey(plaintextKey) {
const baseKey = await window.crypto.subtle.importKey("raw", new TextEncoder().encode(plaintextKey), "PBKDF2", false, ["deriveKey"]);
return window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: new TextEncoder().encode("some-salt"),
iterations: 10000,
hash: "SHA-256"
},
baseKey,
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
}
async function encryptWithKey(text, key) {
const secretKey = await deriveKey(key);
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const cipherText = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
secretKey,
new TextEncoder().encode(text)
);
return {
cipherText: btoa(String.fromCharCode(...new Uint8Array(cipherText))),
iv: btoa(String.fromCharCode(...new Uint8Array(iv)))
};
}
async function decryptWithKey(cipherTextBase64, ivBase64, key) {
const secretKey = await deriveKey(key);
const cipherText = Uint8Array.from(atob(cipherTextBase64), c => c.charCodeAt(0));
const iv = Uint8Array.from(atob(ivBase64), c => c.charCodeAt(0));
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
secretKey,
cipherText
);
return new TextDecoder().decode(new Uint8Array(decrypted));
}
const psk = "my password";
(async () => {
const result = await encryptWithKey("my secret text", psk);
console.log("Encrypted Ciphertext:", result.cipherText);
console.log("Encrypted IV:", result.iv);
const decryptedText = await decryptWithKey(result.cipherText, result.iv, psk);
console.log("Decrypted:", decryptedText);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment