sure/src/routes/receive.ts

81 lines
2.0 KiB
TypeScript

import {
deriveSharedSecret,
decrypt,
retrieveOrGenerateKeyPair,
} from "../utils/crypto";
const MESSAGE_OUTPUT_ID = "message";
const DECRYPT_BUTTON_ID = "decrypt";
const TEMPLATE = `
<section>
<details>
<summary>How it Works</summary>
<ul>
<li>Press "Decrypt" to view the information sent by the sender.</li>
<li>The decrypted message will appear below.</li>
</ul>
</details>
<form>
<input
id="${DECRYPT_BUTTON_ID}"
type="submit"
value="Decrypt"
aria-label="Decrypt"
/>
<textarea
id="${MESSAGE_OUTPUT_ID}"
readonly
aria-label="Decrypted Message"
></textarea>
</form>
</section>
`;
export async function setupReceivePage(
element: HTMLElement,
params: { p: string; iv: string; m: string }
) {
element.innerHTML = TEMPLATE;
// Add an event listener to the "Decrypt" button
const decryptButton = document.getElementById(
DECRYPT_BUTTON_ID
) as HTMLButtonElement;
decryptButton.addEventListener("click", (event: Event) => {
event.preventDefault();
decryptData(params);
});
}
async function decryptData({ p, iv, m }: { p: string; iv: string; m: string }) {
// Parse the 'p' parameter to get publicB
const publicBJwk = JSON.parse(atob(p));
// Import publicB as a CryptoKey
const publicB = await window.crypto.subtle.importKey(
"jwk",
publicBJwk,
{
name: "ECDH",
namedCurve: "P-256",
},
false,
[]
);
const keyPairA = await retrieveOrGenerateKeyPair();
// Retrieve the AES key from local storage
const aesKey = await deriveSharedSecret(keyPairA.privateKey, publicB);
// Decrypt the message using the AES key and IV
const decryptedData = await decrypt(aesKey, iv, m);
// Update the message output with the decrypted message
const messageOutput = document.getElementById(
MESSAGE_OUTPUT_ID
) as HTMLTextAreaElement;
messageOutput.value = decryptedData;
}