How to Encrypt in JavaScript and Decrypt String in PHP using AES and Cryptojs

Parvez Alam
2 min readNov 4, 2016

--

This tutorial help to encrypt and decrypt string using cryptojs and php. Cryptojs is very popular library which is used to convert string data into encrypted text and vise versa.

I am using Angularjs/javascript Cryptojs library for encryption data. You can encrypt and decrypt string, forms data and any header parameters.You can create your own public salt key which will secure your encrypted data. The SALT string is a user defined public key which will use for encryption and decryption of data/string.This example will works with CryptoJS 3.x and PHP5+ with openssl support.

I am using below files for decrypt string in php

Angular application — Angularjs application convert string and send to php application for decrypt data.
index.php – This file responsible to decrypt string using mcrypt_decrypt and display data.

We are using cryptojs Hex method to encode key and iv in angularjs application. I am using below key and iv –

  • key : 0123456789abcdef0123456789abcdef
  • iv : abcdef9876543210abcdef9876543210
  • Encrypted string : MwOfGGCYPBEpQ0ImKQsgyA==

Above salt string is public key which is available only for both party server and front-end side.

Decrypt String in PHP using Cryptojs and AES

There are following php code help to convert encrypted data into plain string.

<?php $key = pack(“H*”, “0123456789abcdef0123456789abcdef”); $iv = pack(“H*”, “abcdef9876543210abcdef9876543210”); $encrypted = base64_decode(‘MwOfGGCYPBEpQ0ImKQsgyA==’); $decrypt_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv); echo $decrypt_string; ?>

$key = pack(“H*”, “0123456789abcdef0123456789abcdef”);

$iv = pack(“H*”, “abcdef9876543210abcdef9876543210”);

$encrypted = base64_decode(‘MwOfGGCYPBEpQ0ImKQsgyA==’);

$decrypt_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv);

I am using mcrypt_decrypt() method for decrypt data and MCRYPT_RIJNDAEL_128 cipher key.
This php tutorial help for basic encryption/decryption string using AES and PHP. You are free to use and customized this code.

You can download source code and Demo from below link.

Originally published at www.phpflow.com on November 4, 2016.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/