-
Notifications
You must be signed in to change notification settings - Fork 13
nodejs encryption decryption
Vijay Pratap edited this page Jul 20, 2024
·
2 revisions
Encryption is the process of converting plain text into a coded format to prevent unauthorized access. Decryption is the reverse process, converting the encrypted data back into its original form so it can be understood.
- Data Security: Protect sensitive information such as passwords and personal data.
- Secure Communication: Ensure that messages sent over the internet are read only by the intended recipient.
- Data Integrity: Prevent data tampering by ensuring that the data has not been altered during transmission.
mkdir nodejs-encryption-demo
cd nodejs-encryption-demo
npm init -y
npm install express crypto-js
Create a file named server.js
and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Welcome to NodeJS Encryption & Decryption Demo');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Add encryption and decryption functions to the sample route:
const crypto = require('crypto-js');
const secretKey = 'mySecretKey';
// Encryption function
const encrypt = (text) => {
return crypto.AES.encrypt(text, secretKey).toString();
};
// Decryption function
const decrypt = (cipherText) => {
const bytes = crypto.AES.decrypt(cipherText, secretKey);
return bytes.toString(crypto.enc.Utf8);
};
app.post('/encrypt', (req, res) => {
const { text } = req.body;
const encryptedText = encrypt(text);
res.send({ encryptedText });
});
app.post('/decrypt', (req, res) => {
const { cipherText } = req.body;
const decryptedText = decrypt(cipherText);
res.send({ decryptedText });
});
Here is the complete code combining all steps:
const express = require('express');
const crypto = require('crypto-js');
const app = express();
app.use(express.json());
const PORT = 3000;
const secretKey = 'mySecretKey';
// Encryption function
const encrypt = (text) => {
return crypto.AES.encrypt(text, secretKey).toString();
};
// Decryption function
const decrypt = (cipherText) => {
const bytes = crypto.AES.decrypt(cipherText, secretKey);
return bytes.toString(crypto.enc.Utf8);
};
app.get('/', (req, res) => {
res.send('Welcome to NodeJS Encryption & Decryption Demo');
});
app.post('/encrypt', (req, res) => {
const { text } = req.body;
const encryptedText = encrypt(text);
res.send({ encryptedText });
});
app.post('/decrypt', (req, res) => {
const { cipherText } = req.body;
const decryptedText = decrypt(cipherText);
res.send({ decryptedText });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});