Data Encryption And Decryption In ReactJS

Hello Developers,

As of now for security purposes, we need to encrypt user’s sensitive informations like email address, mobile no, and most likely passwords but to achieve that we are going to use crypto-js
First, create a new app using the following command :

npx create-react-app your-app-name

Then install crypto-js in your app using the following command :

npm i crypto-js

Then make two functions one to encrypt and the second one to decrypt data

// import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState } from "react";
import CryptoJS from "crypto-js";
import { Button, Form } from "react-bootstrap";

const App = () => {
  const [value, setValue] = useState("");
  const [encrypt, setEncrypt] = useState("");
  const [decrypt, setDecrypt] = useState("");
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  const encryptHandler = () => {
    setEncrypt(
      CryptoJS.AES.encrypt(JSON.stringify(value), "my-secret-key").toString()
    );
  };
  const decryptHandler = () => {
    setDecrypt(
      JSON.parse(
        CryptoJS.AES.decrypt(encrypt, "my-secret-key").toString(
          CryptoJS.enc.Utf8
        )
      )
    );
  };
  return (
    <div className="d-flex flex-column align-items-center">
      <Form onSubmit={(e) => e.preventDefault()} className="w-25">
        <Form.Group className="mb-3">
          <Form.Label title="">Encrypt</Form.Label>
          <Form.Control
            type="text"
            autoComplete="off"
            onChange={handleChange}
          />
        </Form.Group>
        <p>Encrypted text: {encrypt}</p>
        <p>Decrypted text: {decrypt}</p>
        <Button variant="primary" color="danger" onClick={encryptHandler}>
          Encrypt
        </Button>

        <Button
          className="m-3"
          variant="primary"
          color="danger"
          onClick={decryptHandler}
        >
          Decrypt
        </Button>
      </Form>
    </div>
  );
};

export default App;

Here while encrypting data we used a secret key which we need to use for decryption in the future

Make sure your secret key will be vital, here I used a regular key as an example

Example :

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories