I used the following code I found online to do some basic encryption/decryption. It works as expected but I have someone who’s stuck on decrypting it in PHP.
I’m trying to do it myself but my PHP is a bit rusty having not used it for a few years now.
// Checking the crypto module
const crypto = require('crypto');
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Encrypting text
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-ctr', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}
// Decrypting text
function decrypt(text) {
let iv = Buffer.from(text.iv, 'hex');
let encryptedText = Buffer.from(text.encryptedData, 'hex');
let decipher = crypto.createDecipheriv('aes-256-ctr', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
I thought it should look something like this but when testing, I keep getting gibberish output.
openssl_decrypt(base64_decode($encryptedData), "aes-256-ctr", base64_decode($key), OPENSSL_RAW_DATA, hex2bin($iv));
>Solution :
To decrypt data in PHP that was encrypted in Node.js using aes-256-ctr, you’ll need to make sure the key, IV, and encrypted data are correctly transferred and decoded. Here’s how you can do it:
Make sure you have hex-encoded versions of your encrypted data (encryptedData), key (key), and initialization vector (iv) from Node.js.
Use the hex2bin() function in PHP to convert these hex-encoded strings to binary data.
Finally, use openssl_decrypt to decrypt the data.
<?php
// Your hex-encoded encrypted data, key, and iv from Node.js
$encryptedData = "your_hex_encoded_encrypted_data";
$key = "your_hex_encoded_key";
$iv = "your_hex_encoded_iv";
// Convert hex-encoded values to binary
$key = hex2bin($key);
$iv = hex2bin($iv);
$encryptedData = hex2bin($encryptedData);
// Decrypt using openssl_decrypt
$decrypted = openssl_decrypt($encryptedData, "aes-256-ctr", $key, OPENSSL_RAW_DATA, $iv);
// Output the decrypted data
echo $decrypted;
?>
Make sure you replace your_hex_encoded_encrypted_data, your_hex_encoded_key, and your_hex_encoded_iv with the actual hex-encoded strings you have.