skip to Main Content

I am trying to encrypt my password in the frontend (javascript)before I send it to the backend (fastapi, python)
Although many Google searches said crypto can be used, I saw that it works only in the nodejs environment and not in the browser environment

Is there anyway I can achieve encryption in my js frontend so that decryption can be done in the backend?

I see some articles on crypto-js which requires me to install it separately, but apparently we do not have permission to use cryptojs so that had to be ruled out.

Tried using crypto but that did not seem to work

2

Answers


  1. Use https, problem solved.

    The magic in encryption is not the encryption itself, but trusting that you encrypt for the expected receiver. In-browser-encryption can not add any more trust in using the right key than what https provides: the server would need to provide its public key and you have no way to trust it to be the correct key.

    Not what you wanted to hear, but that time/work is better spent where it makes a difference.

    Login or Signup to reply.
  2. You can use Web Cryptography API.

    I have generated, exported, and imported using the same code in node, deno, and bun, and in the browser.

    You can use the same code in the browser by substituting writing and reading files with <input type="file">, <a> element or other options such as WICG File System Access API for reading and writing files locally, and/or use fetch(), WebTransport, WebRTC Data Channels, Web Torrent or other means to send and receive encrypted and decrypted signals over the network.

    const algorithm = { name: "Ed25519" };
    const encoder = new TextEncoder();
    const cryptoKey = await webcrypto.subtle.generateKey(
      algorithm,
      true, /* extractable */
      ["sign", "verify"],
    );
    const privateKey = JSON.stringify(
      await webcrypto.subtle.exportKey("jwk", cryptoKey.privateKey),
    );
    writeFileSync("./privateKey.json", encoder.encode(privateKey));
    const publicKey = JSON.stringify(
      await webcrypto.subtle.exportKey("jwk", cryptoKey.publicKey),
    );
    writeFileSync("./publicKey.json", encoder.encode(publicKey));
    
    const privateKey = fs.readFileSync("./privateKey.json");
    const publicKey = fs.readFileSync("./publicKey.json");
    // https://github.com/tQsW/webcrypto-curve25519/blob/master/explainer.md
    const cryptoKey = {
      privateKey: await webcrypto.subtle.importKey(
        "jwk",
        JSON.parse(decoder.decode(privateKey)),
        algorithm.name,
        true,
        ["sign"],
      ),
      publicKey: await webcrypto.subtle.importKey(
        "jwk",
        JSON.parse(decoder.decode(publicKey)),
        algorithm.name,
        true,
        ["verify"],
      ),
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search