Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created November 9, 2021 21:59
Show Gist options
  • Save mayankchoubey/66b5594556149656a8b0232b7ec93799 to your computer and use it in GitHub Desktop.
Save mayankchoubey/66b5594556149656a8b0232b7ec93799 to your computer and use it in GitHub Desktop.
AES encryption & decryption in Deno
import {
decode as hd,
encode as he,
} from "https://deno.land/std/encoding/hex.ts";
const te = (s: string) => new TextEncoder().encode(s),
td = (d: Uint8Array) => new TextDecoder().decode(d);
const rawKey = new Uint8Array([
238,
17,
126,
165,
51,
88,
22,
218,
53,
172,
137,
113,
210,
198,
109,
117,
]);
const key = await crypto.subtle.importKey(
"raw",
rawKey.buffer,
"AES-CBC",
true,
["encrypt", "decrypt"],
);
const plainText = "Learning Deno is fun!!";
const iv = await crypto.getRandomValues(new Uint8Array(16));
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-CBC", iv },
key,
te(plainText),
);
const encryptedBytes = new Uint8Array(encrypted);
const hexBytes = td(he(encryptedBytes));
console.log("Encrypted hex data", hexBytes);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-CBC", iv },
key,
hd(te(hexBytes)),
);
const decryptedBytes = new Uint8Array(decrypted);
const decryptedText = td(decryptedBytes);
console.log("Decrypted data", decryptedText);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment