Secure Web applications using CryptoJS and PHP
Deepak Singh
Posted on November 27, 2021
Encrypt data using JS on front end and decrypt using PHP on backend using AES encryption method.
Why to use this method
To prevent Man-in-the-middle (MITM) attacks. Maximum cyber attacks occur MITM attacks. It means the attacker can be seen (intercept) your data before the server receives it from your browser. What if the data we send is already encrypted on the browser itself and sent to the server. It is where the crypto-to-php method works.
How to use it
Just encrypt the data using the method below:
CryptoJS.AES.encrypt(JSON.stringify(dataValue), TheSecret, {format: CryptoJSAesJson}).toString();
dataValue is your input value the TheSecret is your secret key. You can use your custom random generated secret key, I have used time() for demo purposes. You can use PHP Encryption Methos for your custom secret key encryption and decryption.
The method I used to achieve the purpose (just for demo purposes).
Start with data encryption on Front-End
var dt = new Date();
var TheSecret = "";
$(document).ready(function(e) {
$.ajax({
url:'libs/php/get_random_key.php',
type:'POST',
data:"dts="+dt.getTime(),
success: function(responseAjx){
TheSecret = responseAjx;
console.log(TheSecret);
}
});
});
$('button[name="sub"]').click(function(e) {
var dataValue = $('input[name="data"]').val();
var enData = CryptoJS.AES.encrypt(JSON.stringify(dataValue), TheSecret, {format: CryptoJSAesJson}).toString();
$.ajax({
url:'libs/php/decrypt.php',
type:'POST',
data:'crypt='+enData,
success: function(cryptResponse){
console.log(cryptResponse);
}
});
});
Here is the JS Encryption and Decryption Library CryptoJS & Method
Here is the get_random_key.php code:
session_start();
$sname = time();
$_SESSION['cryptPs'] = $sname;
echo $sname;
Here is the decrypt.php code:
session_start();
$key = $_SESSION['cryptPs'];
include('aes-encryption.php');
if(isset($_POST)){
echo cryptoJsAesDecrypt($key, $_POST["crypt"]);
}
Find the aes-encryption.php here PHP AES Encryption
Find details code here GitHub
Posted on November 27, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.