Encrypt and Decrypt
NODEJS
const express = require('express')
const app = express()
// Middleware to parse JSON request body
app.use(express.json());
app.post('/', (req, res) => {
// Includes crypto module
const crypto = require('crypto');
// Defining algorithm
const algorithm = 'aes-192-cbc';
// Defining password
const password = 'bncaskdbvasbvlaslslasfhj';
// Defining key
const key = crypto.scryptSync(password, 'GfG', 24);
console.log(key);
// Defininf iv
const iv = Buffer.alloc(16, 0);
console.log(iv);
// Creating decipher
const decipher =
crypto.createDecipheriv(algorithm, key, iv);
// Declaring decrypted
let decrypted = '';
// Reading data
decipher.on('readable', () => {
let chunk;
while (null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8');
}
});
// Handling end event
decipher.on('end', () => {
console.log(decrypted);
});
// Encrypted data which is to be decrypted
const encrypted =
'MfHwhG/WPv+TIbG/qM78qA==';
decipher.write(encrypted, 'base64');
decipher.end();
console.log("done");
// console.log('Request Body:', req.body);
// if (!req.body.encodedEncryptedData) {
// return res.status(400).send('encryptedData is missing');
// }
// const encryptedText = req.body.encodedEncryptedData;
// const iv = req.body.iv;
// const crypto = require('crypto');
// const PRIVATE_KEY = '1234567890abcdef'; // Same key as Salesforce
// const ALGORITHM = 'aes-128-cbc';
// function decryptData(encryptedData, iv) {
// console.log(iv);
// console.log(encryptedData);
// const ivBuffer = Buffer.from(iv, 'base64');
// if (ivBuffer.length !== 16) {
// return res.status(400).send(`Invalid IV length: ${ivBuffer.length}`);
// }
// console.log(ivBuffer.length);
// console.log(PRIVATE_KEY.length);
// const decipher = crypto.createDecipheriv(ALGORITHM, Buffer.from(PRIVATE_KEY), ivBuffer);
// let decrypted = decipher.update(encryptedData);
// console.log(decrypted);
// decrypted = Buffer.concat([decrypted, decipher.final()]);
// return decrypted.toString();
// }
// const decryptedData = decryptData(encryptedText, iv);
res.send({ success: true, message: 'Data received successfully', data: decryptedData });
})
app.listen({ port: process.env.PORT, host: "0.0.0.0" })
APEX
public class EncryptionUtil {
private static final String password = '1234567890abcdef'; // Replace with your actual private key
private static final String salt = 'ewsign'; // Replace with your actual private key
private static Integer keyLength = 24; // Length in bytes
private static Integer iterations = 10000;
private static final String ALGORITHM = 'AES128'; // Ensure compatibility with Node.js
// public static Blob generateKey(
// String password,
// String salt,
// Integer keyLengthBytes,
// Integer iterations
// ) {
// // Convert password and salt to Blob
// Blob passwordBlob = Blob.valueOf(password);
// Blob saltBlob = Blob.valueOf(salt);
// // Generate derived key using PBKDF2
// Blob derivedKey = Crypto.generateDigest(
// 'SHA-256',
// 'password',
// passwordBlob,
// saltBlob,
// iterations
// );
// // Truncate or pad the derived key to the required length
// return derivedKey.toBase64().substring(0, keyLengthBytes);
// }
public static void sendData() {
Http http = new Http();
HttpRequest request = new HttpRequest();
Map<String, Object> encryptionMap = EncryptionUtil.encryptData(
'Hello World'
);
request.setEndpoint('https://encrypt-decrypt-api.glitch.me/');
request.setHeader('Content-Type', 'application/json');
request.setMethod('POST');
String jsonBody = Json.serialize(encryptionMap);
request.setBody(jsonBody);
HttpResponse response = http.send(request);
System.debug('@@@ response ::' + response);
System.debug('@@@ response body ::' + response.getBody());
}
public static Map<String, Object> encryptData(String plainText) {
Blob passwordBlob = Blob.valueOf(password);
Blob key = Crypto.generateDigest('SHA-256', passwordBlob);
// Generate a random 16-byte Initialization Vector (IV)
Blob iv = Crypto.generateAesKey(128);
Blob data = Blob.valueOf(plainText);
// Encrypt the data
Blob encryptedData = Crypto.encryptWithManagedIV(ALGORITHM, key, data);
String ivbase64 = EncodingUtil.base64Encode(iv);
String encodedEncryptedData = EncodingUtil.base64Encode(encryptedData);
return new Map<String, Object>{
'iv' => ivbase64,
'encodedEncryptedData' => encodedEncryptedData
};
}
}
Comments
Post a Comment