Skip to content

Instantly share code, notes, and snippets.

@sno2
Last active May 18, 2021 20:29
Show Gist options
  • Save sno2/892f9d6de33a0428f25d2094163baff6 to your computer and use it in GitHub Desktop.
Save sno2/892f9d6de33a0428f25d2094163baff6 to your computer and use it in GitHub Desktop.
import { AES } from "https://deno.land/x/god_crypto/aes.ts";
import { encode, decode } from "https://deno.land/[email protected]/encoding/hex.ts";
class SecretStore {
#aes: AES;
constructor(data: { key: string; iv?: string }) {
this.#aes = new AES(data.key, {
mode: "cbc",
iv: data.iv ?? "random 16byte iv",
});
}
async setItem(name: string, value: string): Promise<void> {
const encryptedBytes = await this.#aes.encrypt(
encode(new TextEncoder().encode(value))
);
const hash = encode(encryptedBytes);
console.log(encryptedBytes.hex());
localStorage.setItem(name, new TextDecoder().decode(hash));
}
async getItem(name: string): Promise<null | string> {
const encrypted = localStorage.getItem(name);
if (encrypted === null) return null;
const decrypted = await this.#aes.decrypt(
decode(new TextEncoder().encode(encrypted))
);
return new TextDecoder().decode(
decode(decode(new TextEncoder().encode(decrypted.hex())))
);
}
}
const store = new SecretStore({ key: "thegrassisgreen_" });
await store.setItem("password", "foo");
console.log(localStorage.getItem("password"));
console.log(await store.getItem("password"));
@sno2
Copy link
Author

sno2 commented May 18, 2021

Working now thanks to lucas 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment