Created
December 2, 2022 09:42
-
-
Save prateek-mt/b2a39aa54226ec86b2205f8e465cdb38 to your computer and use it in GitHub Desktop.
a simple encryption and decryption code in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A node demo program for creating the ECDH | |
// Importing the crypto module | |
const crypto = require('crypto'); | |
// import crypto from 'crypto' | |
// Initializing the algorithm | |
const algorithm = 'aes-256-cbc'; | |
// Initializing the key | |
const key = Buffer.from("48b1db4df28757ba48b1db4df28757ba"); | |
// Initializing the iv vector | |
// const iv = Buffer.from("1111111122222222"); | |
// const iv = crypto.randomBytes(16); | |
// Encrypt function to encrypt the data | |
function encrypt(text) { | |
iv = crypto.randomBytes(16); | |
// crypto.subtle.decrypt() | |
// Creating the cipher with the above defined parameters | |
let cipher = | |
crypto.createCipheriv(algorithm, Buffer.from(key)); | |
// Updating the encrypted text... | |
let encrypted = cipher.update(text); | |
// Using concatenation | |
encrypted = Buffer.concat([encrypted, cipher.final()]); | |
// Returning the iv vector along with the encrypted data | |
return { iv: iv.toString('hex'), | |
encryptedData: encrypted.toString('hex') }; | |
} | |
//Decrypt function for decrypting the data | |
function decrypt(output) { | |
// Creating the decipher from algo, key and iv | |
let decipher = crypto.createDecipheriv( | |
algorithm, Buffer.from(key), Buffer.from(output.iv, 'hex')); | |
// Updating decrypted text | |
let decrypted = decipher.update(Buffer.from(output.encryptedData, 'hex')); | |
decrypted = Buffer.concat([decrypted, decipher.final()]); | |
// returning response data after decryption | |
return decrypted.toString(); | |
} | |
console.time("encryption time :") | |
for (let i = 0; i < 1; i++) { | |
// Encrypting the below data and printing output | |
var output = encrypt("Welcome to TutorialsPoint !" + i); | |
// console.log("Encrypted data -- ", output); | |
// console.log("Decrypted data -- ", decrypt(output)); | |
} | |
console.timeEnd("encryption time :") | |
//Printing decrypted data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment