Skip to content

Instantly share code, notes, and snippets.

@widada
Created April 4, 2024 01:50
Show Gist options
  • Save widada/8ccf6c88428b4a3c8a5b3c2fd51fd44d to your computer and use it in GitHub Desktop.
Save widada/8ccf6c88428b4a3c8a5b3c2fd51fd44d to your computer and use it in GitHub Desktop.
Encypt Body Request

Example code in the Frontend

import React from 'react';
import CryptoJS from 'crypto-js';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: '' };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit() {
    // Prepare data to be encrypted (e.g., JSON object)
    const data = JSON.stringify({
      name: 'Superman',
      class: 'S rank'
    });

    // Generate a random IV (Initialization Vector)
    const iv = CryptoJS.lib.WordArray.random(16); // IV acak

    // Encrypt the data using AES-256-CBC algorithm
    const encryptedData = CryptoJS.AES.encrypt(data, 'secret-key', { iv: iv }).toString();

    // Send the encrypted data and IV to the backend
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ encryptedData, iv: iv.toString() }),
    };

    fetch('http://localhost:2000/submit-data', requestOptions)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }

  render() {
    return (
      <div>
        <button onClick={this.handleSubmit}>Submit Encrypted Data</button>
      </div>
    );
  }
}

export default App;

Example Code in the Backend

const express = require('express');
const bodyParser = require('body-parser');
const CryptoJS = require('crypto-js');
const cors = require('cors')

const app = express();
const PORT = 2000;

app.use(bodyParser.json());
app.use(cors({ origin: 'http://localhost:3000'})) 

app.post('/submit-data', (req, res) => {
  const encryptedData = req.body.encryptedData;
  const iv = req.body.iv;
  
  // Decrypt data
  const decryptedData = CryptoJS.AES.decrypt(encryptedData, 'secret-key', { iv: iv }).toString(CryptoJS.enc.Utf8);
  
  // do the next logic after decrypt
  console.log('Decrypted data:', decryptedData);

  res.json(JSON.parse(decryptedData));
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment