This content originally appeared on DEV Community and was authored by Deepak Singh
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
This content originally appeared on DEV Community and was authored by Deepak Singh

Deepak Singh | Sciencx (2021-11-27T10:23:44+00:00) Secure Web applications using CryptoJS and PHP. Retrieved from https://www.scien.cx/2021/11/27/secure-web-applications-using-cryptojs-and-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.