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.

Revisions

  1. sno2 revised this gist May 18, 2021. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions safe_store.ts
    Original file line number Diff line number Diff line change
    @@ -25,10 +25,10 @@ class SecretStore {
    const encrypted = localStorage.getItem(name);
    if (encrypted === null) return null;
    const decrypted = await this.#aes.decrypt(
    new TextEncoder().encode(encrypted)
    decode(new TextEncoder().encode(encrypted))
    );
    return new TextDecoder().decode(
    decode(new TextEncoder().encode(decrypted.hex()))
    decode(decode(new TextEncoder().encode(decrypted.hex())))
    );
    }
    }
  2. sno2 revised this gist May 18, 2021. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion safe_store.ts
    Original file line number Diff line number Diff line change
    @@ -13,9 +13,11 @@ class SecretStore {

    async setItem(name: string, value: string): Promise<void> {
    const encryptedBytes = await this.#aes.encrypt(
    new TextEncoder().encode(value)
    encode(new TextEncoder().encode(value))
    );
    const hash = encode(encryptedBytes);
    console.log(encryptedBytes.hex());

    localStorage.setItem(name, new TextDecoder().decode(hash));
    }

  3. sno2 created this gist May 18, 2021.
    38 changes: 38 additions & 0 deletions safe_store.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    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(
    new TextEncoder().encode(value)
    );
    const hash = encode(encryptedBytes);
    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(
    new TextEncoder().encode(encrypted)
    );
    return new TextDecoder().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"));