Last active
May 18, 2021 20:29
-
-
Save sno2/892f9d6de33a0428f25d2094163baff6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working now thanks to lucas 🎉