Perform payload encryption in React

Whenever we have to exchange sensitive information it is always recommended to send the data in an encrypted format over the network.

One of the secure ways to do so is to use asymmetric encryption using a public and private key pair.

Let us see how we can create a JWE key from the payload and send it in the payload.

First, generate a pair of RSA keys and use the public key for encryption (on the client side) and the private key for decryption (on the server side) and vice versa.

Import the public key in the browser and then use the JOSE package to encrypt the payload.

import * as jose from "jose";

const encrypt = async function () {
  try {
    // public key
    const pemEncodedKey = `-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArIJnjwOZJsraOXwxkfYsCfxpMJVwYewHA/j3BE3pa1wfp2ptG+xDClt2RsFoDIUalq2/fJDnIsfUG9DEuPkMg47Hn91EfpLgHUlBgnF/jJ08EZhN8yKPQlM2OJhFzc6Aak8a56Jczw4VvT4dHJ414EfnzcPF1pBpfP5OeXQrIQ4rPbbt/umyyTei/MqrtMfUnbJUoWZ2/70Uj2YW5QdoBXPS9k6DwaSIwnjfSIXkfab5tr2xidjjYkOJ9fWbtqFK8d4/yFzsw84rRrZQl35+ymkQf4aVXrm3RDuSxJjGgTvP6R4h2CGGEA7pK/ckmAghio3B43mtKbvDhB8AvFzRSwIDAQAB
    -----END PUBLIC KEY-----`;

    // load the public key
    let publicKey = await importKey(pemEncodedKey);

    const body = {
      searchType: "CARD_NO",
      cardNumber: "1111420000001111",
      customerId: "1234",
      lastFourDigits: "1234",
    };

    // generate the jwe key from the string 
    const jwe = await new jose.CompactEncrypt(new TextEncoder().encode(JSON.stringify(body)))
      .setProtectedHeader({ alg: "RSA-OAEP-256", enc: "A256GCM" })
      .encrypt(publicKey);

    // print the key
    console.log(jwe);

    // send this JWE key as data in the api call
  } catch (e) {
    console.log(e);
  }
};

Choose the algorithm RSA-OAEP-256 and encryption method A256GCM according to your requirement.

Input:
encrypt();

Output:
// jwe key
eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.Yf5k5wwSKfout1TIQM4m6oAgVuOWg9aom8syspW5H4t38l7eG8DJ0k07uigb9NgXFAPZgmU3sMmY2oG5rVy_M1cz55XIBWQDdYGq_I1bdRCPXX4m5RwAZdnlIg_rqLR07zfQC6BBu5PbmgfqDq9532FosgECBEfqThvv7a4ZNg_2Og4q4u2FHSsDfcJ8QU6dwpIdhEhfCaPw9bhiF2t4iLLKVGrZaYGQZnjNHBfcwWqRwSgaj7Z8R587eK4FIjglGSICVdSezm5wPWdwXnn2D1_BcF5TPDCzYUnip6MSyEMKvc8qeSZLYLHng-d2sK6fbQW5ztLUsJqvezt61YQKwA.H9cnHUZYdKAOJMR4.CVOgVUqKlFRl4ASDN91XgKVichS0M1IsKQiTq2e_Tm7RRSCq1ALTviiWZ0kCMN4MzOikYVU0yNjOBpr6R3LImLUPTexfhfH_6IGQa4fFvjuLOIl3QBrD5O6Ujh2KXWlF5dRw7A.VeBe8H7ZXJeyMQte9Zyo4w