Different AES Encrypt in JavaScript and PHP - javascript

I want to encrypt a data with PHP.
I before used from a javascript code to encrypt.
JavaScript Code:
const SHARED_KEY="XXelkee4v3WjMP81fvjgpNRs2u2cwJ7n3lnJzPt8iVY=";
const ZERO_IV=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
let data="6104337983063890";
aesEncrypt = async (data) => {
try{
let key = new Uint8Array(this.base64ToArray(SHARED_KEY));
let aes = new aesJs.ModeOfOperation.cbc(key, ZERO_IV)
let bData = aesJs.utils.utf8.toBytes(data);
let encBytes = aes.encrypt(aesJs.padding.pkcs7.pad(bData))
return this.arrayToHex(encBytes)
}catch(err) {
console.error(err)
return null
}
}
PHP Code:
$sharedSecret=base64_decode('XXelkee4v3WjMP81fvjgpNRs2u2cwJ7n3lnJzPt8iVY=');
$iv = '0000000000000000';
$data="6104337983063890";
$output = openssl_encrypt(
$data,
'AES-128-CBC',
$sharedSecret,
OPENSSL_RAW_DATA,
$iv
);
$output=bin2hex($output);
Output in two languages is:
JavaScript: 4b685c988d9e166efd0bc5830e926ae0d60111d9dd73d7b4f3c547282994546f (Correct)
PHP: 091da5cf4ffd853e58f5b4f0a07902219ce7ac9647801af5b3e8f755d63b71b4
I need encrypt with PHP that give me same with JavaScript.

You must use aes-256-cbc as algorithm in the PHP code, because the key is 32 bytes large.
Also you have to apply a zero vector as IV in the PHP code, which you can create with:
$iv = hex2bin('00000000000000000000000000000000');
This way, the PHP code provides the same ciphertext as the JavaScript code.
Note that a static IV is insecure. The correct way is to generate a random (non-secret) IV for each encryption and pass this IV along with the ciphertext to the decrypting side (typically concatenated).

Related

How to decrypt AES256 data which was encrypted on PHP and get value in Javascript?

I have encrypted some value using aes-256-cbc mode on PHP like this:
public function encrypt(string $data): string
{
$iv = $this->getIv();
$encryptedRaw = openssl_encrypt(
$data,
$this->cryptMethod, //aes-256-cbc
$this->key,
OPENSSL_RAW_DATA,
$iv
);
$hash = hash_hmac('sha256', $encryptedRaw, $this->key, true);
return base64_encode( $iv . $hash . $encryptedRaw );
}
Then I tried to decrypt it on PHP and it works fine:
public function decrypt(string $data): string
{
$decoded = base64_decode($data);
$ivLength = openssl_cipher_iv_length($this->cryptMethod);
$iv = substr($decoded, 0, $ivLength);
$hmac = substr($decoded, $ivLength, $shaLength = 32);
$decryptedRaw = substr($decoded, $ivLength + $shaLength);
$originalData = openssl_decrypt(
$decryptedRaw,
$this->cryptMethod,
$this->key,
OPENSSL_RAW_DATA,
$iv
);
So I'm new to JavaScript and I don't know how to realize the same decrypt method as on php.
Example of encrypted string and it's key:
encrypted string lUIMFpajICh/e44Mwkr0q9xdyJh5Q8zEJHi8etax5BRl78Vsyh+wDknmBga1L8p8SDZA6WKz1CvAAREFGreRAQ== secret key - 9SJ6O6IwmItSRICbXgdJ
Example what I found returns empty string:
const decodedString = base64.decode(
`lUIMFpajICh/e44Mwkr0q9xdyJh5Q8zEJHi8etax5BRl78Vsyh+wDknmBga1L8p8SDZA6WKz1CvAAREFGreRAQ==`
);
const CryptoJS = require("crypto-js");
var key = CryptoJS.enc.Latin1.parse("9SJ6O6IwmItSRICbXgdJ");
var iv = CryptoJS.enc.Latin1.parse(decodedString.slice(0, 16));
var ctx = CryptoJS.enc.Base64.parse(
"lUIMFpajICh/e44Mwkr0q9xdyJh5Q8zEJHi8etax5BRl78Vsyh+wDknmBga1L8p8SDZA6WKz1CvAAREFGreRAQ=="
);
var enc = CryptoJS.lib.CipherParams.create({ ciphertext: ctx });
console.log(
CryptoJS.AES.decrypt(enc, key, { iv: iv }).toString(CryptoJS.enc.Utf8)
);
}
What I did wrong?
The key used in the PHP code is only 20 bytes in size and thus too small for AES-256 (AES-256 requires a 32 bytes key). PHP/OpenSSL implicitly pads the key with 0x00 values to the required key length. In the CryptoJS code, this must be done explicitly.
Furthermore, in the CryptoJS code, IV (the first 16 bytes), HMAC (the following 32 bytes) and ciphertext (the rest) are not separated correctly.
Also, the authentication is missing. To do this, the HMAC for the ciphertext must be determined using the key and compared with the HMAC sent. Decryption only takes place if authentication is successful.
If all of this is taken into account, the posted code can be fixed e.g. as follows:
var key = CryptoJS.enc.Utf8.parse("9SJ6O6IwmItSRICbXgdJ".padEnd(32, "\0")); // pad key
var ivMacCiphertext = CryptoJS.enc.Base64.parse("lUIMFpajICh/e44Mwkr0q9xdyJh5Q8zEJHi8etax5BRl78Vsyh+wDknmBga1L8p8SDZA6WKz1CvAAREFGreRAQ==")
var iv = CryptoJS.lib.WordArray.create(ivMacCiphertext.words.slice(0, 4)); // get IV
var hmac = CryptoJS.lib.WordArray.create(ivMacCiphertext.words.slice(4, 4 + 8)); // get HMAC
var ct = CryptoJS.lib.WordArray.create(ivMacCiphertext.words.slice(4 + 8)); // get Ciphertext
var hmacCalc = CryptoJS.HmacSHA256(ct, key);
if (hmac.toString() === hmacCalc.toString()) { // authenticate
var dt = CryptoJS.AES.decrypt({ciphertext: ct}, key, { iv: iv }).toString(CryptoJS.enc.Utf8); // decrypt
console.log(dt);
} else {
console.log("Decryption failed");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
A few thoughts for you:
Check that your encoding/decoding is working properly. For each stage
of the process, endode/decode, then console log the output and
compare input to output, and also between PHP and javascript.
CBC mode uses padding to fill out the blocks. Check that both stacks
are using the same padding type.
Rather than using CBC and a separate HMAC, how about jumping to AEAD (like AES
GCM) which avoids the padding issue, and also incorporates the MAC
into the encryption, so is a more simple interface?

I tried crypto-js but the output is not correct, please see my code and correct me where I am wrong

I have a simple_crypt function in my backend which is working properly, now what I want is to make a similar function for javascript which for exactly the same as the php one.
So I have researched and got the CryptoJS library, my 'Key' and 'iv' values are correct as compared to the PHP one but when I encrypt my string the output is totally different.
This is my working PHP code and I want to convert this into javascript.
<?php
function simple_crypt( $string ) {
$secret_key = '1234567890';
$secret_iv = '0987654321';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
echo "Key : ".$key."<br>";
echo "iv : ".$iv."<br>";
$output = openssl_encrypt( $string, $encrypt_method, $key, 0, $iv );
return $output;
}
$e = simple_crypt("text");
echo $e;
echo "<br>";
?>
This is my JS code in which I am getting the issue, please have a look and tell me where I am wrong in this js code.
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js" integrity="sha512-nOQuvD9nKirvxDdvQ9OMqe2dgapbPB7vYAMrzJihw5m+aNcf0dX53m6YxM4LgA9u8e9eg9QX+/+mPu8kCNpV2A==" crossorigin="anonymous"></script>
<script type="text/javascript">
function simple_crypt(string) {
var secret_key, secret_iv, output, key, iv;
secret_key = '1234567890';
secret_iv = '0987654321';
output = false;
key = CryptoJS.SHA256(secret_key).toString();
iv = CryptoJS.SHA256(secret_iv).toString().substr(0, 16);
console.log("key",key);
console.log("iv",iv);
var encrypted = CryptoJS.AES.encrypt(string, key, {iv: iv});
return (encrypted.toString());
}
console.log(simple_crypt("text"));
</script>
Here is the output:
PHP: T4F65n4AVlmkkb5LLFhRIQ==
JS: U2FsdGVkX18HJGpPYZPm6crBcxA7TfbZZ9Sc/4qHGBk=
So that both codes produces the same result, the key and IV in the NodeJS Code must be the same as in the PHP code and passed as WordArrays. For this, the key and IV you have generated must be further processed as follows:
key = CryptoJS.enc.Utf8.parse(key.substr(0, 32));
iv = CryptoJS.enc.Utf8.parse(iv);
In the PHP code, the SHA256 hash is returned as hex string. With hex encoding the number of bytes doubles, i.e. a SHA256 hash is hex encoded 64 bytes. PHP implicitly considers only the first 32 bytes regarding the key for AES-256, i.e. ignores the last 32 bytes. In the CryptoJS code this must happen explicitly (for the IV this happens, but for the key this is missing).
By parsing with the UTF8 encoder, key and IV are converted into WordArrays. If the key is passed as a string (as in the code posted in the question), then CryptoJS interprets the value as a password and uses a key derivation function to derive key and IV (which is incompatible with the logic in the PHP code).
With the above changes, the CryptoJS code gives the same result as the PHP code:
function simple_crypt(string) {
var secret_key, secret_iv, output, key, iv;
secret_key = '1234567890';
secret_iv = '0987654321';
output = false;
key = CryptoJS.SHA256(secret_key).toString();
iv = CryptoJS.SHA256(secret_iv).toString().substr(0, 16);
key = CryptoJS.enc.Utf8.parse(key.substr(0, 32));
iv = CryptoJS.enc.Utf8.parse(iv);
console.log("key",key.toString());
console.log("iv",iv.toString());
var encrypted = CryptoJS.AES.encrypt(string, key, {iv: iv});
return (encrypted.toString());
}
console.log(simple_crypt("text")); // T4F65n4AVlmkkb5LLFhRIQ==
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
Please note the following:
Using SHA256 to derive the key from a password is insecure. For this purpose, a reliable key derivation function such as PBKDF2 should be used.
For security reasons, a key/IV pair may only be applied once. Therefore, the IV is usually randomly generated for each encryption. The IV is not a secret and is commonly sent to the recipient along with the ciphertext (usually prepended). Alternatively, the IV can be derived together with the key using a KDF (in combination with a randomly generated salt).

Achieve same encryption using CryptoJS (JAVASCRIPT) and OpenSSL (PHP)

I would like to implement a PhP encryption function in a ReactJS application. I need to send the token in the specific format which was created with the OpenSSL library function (openssl_encrypt).
The PHP function produces a few character shorter string in comparison to the JAVASCRIPT function. Of course, both get the same attributes and properties.
PHP:
protected static function encrypt($stringData) {
$encrypted = false;
$encrypt_method = 'AES-256-CBC';
$iv = substr(hash('sha256', static::$ivMessage), 0, 16);
$encrypted= openssl_encrypt($stringData, $encrypt_method, static::$apiSecret, 0, $iv);
return $encrypted;
}
JAVASCRIPT:
export const encrypt = (stringData) => {
const iv = CryptoJS.SHA256(IV_MESSAGE).toString(CryptoJS.enc.Hex).substring(0, 16);
const encrypted = CryptoJS.AES.encrypt(stringData, API_SECRET, {
iv,
mode: CryptoJS.mode.CBC,
pad: CryptoJS.pad.ZeroPadding,
});
return encrypted;
};
Sample constants:
const stringData = "{"uid":19,"price":10000000,"duration":240,"credit_purpose":5,"new_tab":false,"cssFile":"kalkulatorok","css":[],"supported":false,"email":"test#test.hu","productType":"home_loan","method":"calculator","calculatorType":"calculator","unique":true}";
const IV_MESSAGE = "a";
const API_SECRET = "secret_key";
(same for PHP function --> $stringData, $ivMessage; $apiSecret)
How can I achieve to "replicate" the PHP function in JAVASCRIPT? What did I miss so far?
The following changes in the CryptoJS code are necessary to generate the ciphertext of the PHP code:
The key must be passed as WordArray. If it is passed as a string, it is interpreted as a passphrase from which a 32 bytes key is derived.
PHP pads too short keys with 0x00 values up to the specified length. CryptoJS does not do this and (due to a bug) generally uses undefined round numbers for AES in case of invalid keys, so that no matching ciphertext is to be expected.
PKCS7 padding is used in the PHP code (see comment). This must also be applied in CryptoJS code, which however is the default (as well as the CBC mode).
The following PHP code:
function encrypt($stringData) {
$ivMessage = "a";
$apiSecret = "secret_key";
$encrypted = false;
$encrypt_method = 'AES-256-CBC';
$iv = substr(hash('sha256', $ivMessage), 0, 16);
$encrypted= openssl_encrypt($stringData, $encrypt_method, $apiSecret, 0, $iv);
return $encrypted;
}
$stringData = '{"uid":19,"price":10000000,"duration":240,"credit_purpose":5,"new_tab":false,"cssFile":"kalkulatorok","css":[],"supported":false,"email":"test#test.hu","productType":"home_loan","method":"calculator","calculatorType":"calculator","unique":true}';
print(encrypt($stringData) . "\n");
returns the result:
d/H+FfTaT/3tIkaXtIix937p6Df/vlnxagNJGJ7ljj48phT7oA7QssTatL3WNZY0Igt0r5ObGyCt0AR0IccVTFVZdR+nzNe+RmKQEoD4dj0mRkZ7qi/y3bAICRpFkP3Nz42fuILKApRtmZqGLTNO6dwlCbUVvjg59fgh0wCzy15g51G6CYLsEHa89Dt193g4qcXRWFgI9gyY1Gq7FX0G6Ers0fySQjjNcfDJg0Hj5aSxbPU6EPn14eaWqkliNYSMqzKhe0Ev7Y54x2YlUCNQeLZhwWRM2W0N+jGU7W+P/bCtF4Udwv4cweUESXkHLGtlQ0K6O5etVJDtb7ZtdEI/sA==
The CryptoJS code below generates the same ciphertext:
const IV_MESSAGE = "a";
const API_SECRET = "secret_key\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
function encrypt(stringData){
const iv = CryptoJS.SHA256(IV_MESSAGE).toString(CryptoJS.enc.Hex).substring(0, 16);
const encrypted = CryptoJS.AES.encrypt(
stringData,
CryptoJS.enc.Utf8.parse(API_SECRET),
{
iv: CryptoJS.enc.Utf8.parse(iv)
});
return encrypted;
};
const stringData = {"uid":19,"price":10000000,"duration":240,"credit_purpose":5,"new_tab":false,"cssFile":"kalkulatorok","css":[],"supported":false,"email":"test#test.hu","productType":"home_loan","method":"calculator","calculatorType":"calculator","unique":true};
const ciphertextB64 = encrypt(JSON.stringify(stringData)).toString();
console.log(ciphertextB64.replace(/(.{64})/g,'$1\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
The following should also be taken into account:
It is more reliable to avoid encoding the IV as hex string when generating the IV and to directly use the binary data. Otherwise, you also have to keep in mind that depending on the platform, different upper/lower case of the hex numbers can generally be applied. Here this is not critical, since in both cases lower case is used.
If you should really apply a passphrase like secret_key as key, you should also use a reasonable key derivation function (e.g. PBKDF2 in combination with a randomly generated salt) because of the low entropy. The default KDF used in CryptoJS, the proprietary OpenSSL function EVP_BytesToKey, should not be applied because it is not a standard and is also deemed relatively insecure.
For security reasons no static IV may be used. Instead, a randomly generated IV should be applied for each encryption. The IV is not secret and is usually concatenated with the ciphertext in the order IV, ciphertext (see comment).

JS Decrypt Laravel Encrypted String

I have to decrypt laravel 6 encrypted string with javascript.
Key in laravel .env file
APP_KEY=base64:Rva4FZFTACUe94+k+opcvMdTfr9X5OTfzK3KJHIoXyQ=
And in config/app.php file cipher is set to following...
'cipher' => 'AES-256-CBC',
What I have tried so far is given below...
Laravel Code
$test = 'this is test';
$encrypted = Crypt::encrypt($test);
HTML and Javascript Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
var encrypted = 'eyJpdiI6IlB4NG0ra2F6SE9PZmVcL0lpUEFIeVlnPT0iLCJ2YWx1ZSI6IlVMQWJyVjcrcUVWZE1jQ25LbG5NTGRla0ZIOUE2MFNFXC9Ed2pOaWJJaXIwPSIsIm1hYyI6IjVhYmJmZDBkMzAwYzMzYzAzY2UzNzY2';
var key = 'Rva4FZFTACUe94+k+opcvMdTfr9X5OTfzK3KJHIoXyQ='; // this is laravel key in .env file
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
console.log(decrypted);
Console out put of the above code is given below in screenshot...
I have tried so many other JS pieces of code from google and stack overflow, but no luck.
Update
This is requirement to decrypt string in separate offline system. I am not going to dcrypt with javascript on live website. Rather decryption with java script will be done on offline system.
This is how you decrypt a text in javascript encoded with Laravel using AES-256-CBC as the cipher.
CryptoJS 4.0 is used...
// Created using Crypt::encryptString('Hello world.') on Laravel.
// If Crypt::encrypt is used the value is PHP serialized so you'll
// need to "unserialize" it in JS at the end.
var encrypted = 'eyJpdiI6ImRIN3QvRGh5UjhQNVM4Q3lnN21JNFE9PSIsInZhbHVlIjoiYlEvNzQzMnpVZ1dTdG9ETTROdnkyUT09IiwibWFjIjoiM2I4YTg5ZmNhOTgyMzgxYjcyNjY4ZGFkNTc4MDdiZTcyOTIyZjRkY2M5MTM5NTBjMmMyZGMyNTNkMzMwYzY3OCJ9';
// The APP_KEY in .env file. Note that it is base64 encoded binary
var key = 'E2nRP0COW2ohd23+iAW4Xzpk3mFFiPuC8/G2PLPiYDg=';
// Laravel creates a JSON to store iv, value and a mac and base64 encodes it.
// So let's base64 decode the string to get them.
encrypted = atob(encrypted);
encrypted = JSON.parse(encrypted);
console.log('Laravel encryption result', encrypted);
// IV is base64 encoded in Laravel, expected as word array in cryptojs
const iv = CryptoJS.enc.Base64.parse(encrypted.iv);
// Value (chipher text) is also base64 encoded in Laravel, same in cryptojs
const value = encrypted.value;
// Key is base64 encoded in Laravel, word array expected in cryptojs
key = CryptoJS.enc.Base64.parse(key);
// Decrypt the value, providing the IV.
var decrypted = CryptoJS.AES.decrypt(value, key, {
iv: iv
});
// CryptoJS returns a word array which can be
// converted to string like this
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
console.log(decrypted); // VoilĂ ! Prints "Hello world!"
Like #Dusan Malusev already mentioned:
You should not use Laravel APP_KEY in frontend code. NEVER, Laravel uses APP_KEY to encrypt everything including cookies (Session cookie and csrf cookie).
Your application could be hacked if it's in your html code! To answer your question a bit: use Crypt::decrypt($encrypted) on the server side of your application (within Laravel).
Never use your Laravel APP_KEY in frontend. It is a big software vulnerability.
You should create a trait that encrypts and decrypts data before setting and getting data.
To use Laravel Crypt add Encryptable.php
<?PHP
namespace App;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable)) {
$value = Crypt::decrypt($value);
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
After that you can use this trait in your models. Add a $encryptable property. Array of columns to be encrypted and decrypted.
class User extends Model
{
use Encryptable;
protected $encryptable = [
'column',
'anotherColumn',
];
}
After that use model as you use before.
I have used in ReactJs
CryptoJS 4.1
let key = process.env.REACT_APP_ENCRYTO_KEY
let encrypted = atob(response.data)
encrypted = JSON.parse(encrypted)
const iv = CryptoJS.enc.Base64.parse(encrypted.iv)
const value = encrypted.value
key = CryptoJS.enc.Base64.parse(key)
let decrypted = CryptoJS.AES.decrypt(value, key, {
iv
})
decrypted = decrypted.toString(CryptoJS.enc.Utf8)
return {
...response,
data: JSON.parse(decrypted)
}
Laravel 8.x using Encrypter
$encrypter = new Encrypter(Encrypter::generateKey('supported_any_cipher'));
return response($encrypter->encryptString(json_encode($response)), 200);
The supported cipher algorithms and their properties.
['aes-128-cbc' => ['size' => 16, 'aead' => false],
'aes-256-cbc' => ['size' => 32, 'aead' => false],
'aes-128-gcm' => ['size' => 16, 'aead' => true],
'aes-256-gcm' => ['size' => 32, 'aead' => true]]

AES 256 on the client side (JS) and in the server (PHP)

I'm trying to encrypt and decrypt data on the server side and the client using the same type of operation, which is AES-256.
On the server I use PHP and client I use CryptoJS so far I could only encrypt and decrypt the client on the server, see the code:
JS
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/pbkdf2.js"></script>
<script>
var salt = CryptoJS.lib.WordArray.random(128/8);
var key256Bits500Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32, iterations: 500 });
var iv = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
var encrypted = CryptoJS.AES.encrypt("Message", key256Bits500Iterations, { iv: iv });
var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
var iv_base64 = encrypted.iv.toString(CryptoJS.enc.Base64);
var key_base64 = encrypted.key.toString(CryptoJS.enc.Base64);
</script>
PHP
<?php
$encrypted = base64_decode("data_base64"); // data_base64 from JS
$iv = base64_decode("iv_base64"); // iv_base64 from JS
$key = base64_decode("key_base64"); // key_base64 from JS
$plaintext = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv ), "\t\0 " );
How can I encrypt and decrypt data on both sides (client and server) so that communicate in the same language using PHP and CryptoJS?
Your code looks fine apart from a padding mismatch. CryptoJS uses PKCS#5/PKCS#7 padding by default whereas MCrypt only supports ZeroPadding.
If you're only sending textual plaintexts, then you can safely use
CryptoJS.AES.encrypt("Message", key, { iv: iv, padding: CryptoJS.pad.ZeroPadding });
If not, then you should use proper pkcs7unpad in PHP:
$plaintext = pkcs7unpad( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv ), 16 );
Other problems with your code are that you directly use CryptoJS.AES.encrypt(...).toString(). This will create an OpenSSL formatted string which is not purely the ciphertext. You need to use
CryptoJS.AES.encrypt(...).ciphertext.toString(CryptoJS.enc.Base64);
to also be sure about the encoding.
Right now, this is only obfuscation, since you're sending the key along with the ciphertext. I suspect that you want to derive the key in PHP too. If yes, then you will only need to send the random salt along with the ciphertext under the assumption that the server knows the password.
PHP provides a PBKDF2 implementation from version 5.5 onwards.
Full JavaScript part without PBKDF2 involvement:
var message = 'My string - Could also be an JS array/object';
var iv = 'a1a2a3a4a5a6a7a8b1b2b3b4b5b6b7b8';
var key = 'c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8'; // 256-bit hex encoded
var keyBytes = CryptoJS.enc.Hex.parse(key);
var ivBytes = CryptoJS.enc.Hex.parse(iv);
var encrypt = CryptoJS.AES.encrypt(message, keyBytes, {
iv: ivBytes,
padding: CryptoJS.pad.ZeroPadding
}).ciphertext.toString(CryptoJS.enc.Base64);
produces:
j86KHBVRsDGKUnOiYdkEotsFL/lY/1tzz/h3Ay+vlEX11fC055m7vaF6q7w13eUj
Full PHP part without PBKDF2 involvement:
<?php
$iv = 'a1a2a3a4a5a6a7a8b1b2b3b4b5b6b7b8';
$key = 'c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8';
$ct = 'j86KHBVRsDGKUnOiYdkEotsFL/lY/1tzz/h3Ay+vlEX11fC055m7vaF6q7w13eUj';
$ivBytes = hex2bin($iv);
$keyBytes = hex2bin($key);
$ctBytes = base64_decode($ct);
$decrypt = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $keyBytes, $ctBytes, MCRYPT_MODE_CBC, $ivBytes));
echo $decrypt;
produces:
My string - Could also be an JS array/object
The same is possible with the OpenSSL extension:
<?php
$iv = 'a1a2a3a4a5a6a7a8b1b2b3b4b5b6b7b8';
$key = 'c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8c1c2c3c4c5c6c7c8d1d2d3d4d5d6d7d8';
$ct = 'j86KHBVRsDGKUnOiYdkEotsFL/lY/1tzz/h3Ay+vlEX11fC055m7vaF6q7w13eUj';
$ivBytes = hex2bin($iv);
$keyBytes = hex2bin($key);
$ctBytes = base64_decode($ct);
$decrypt = openssl_decrypt($ctBytes, "aes-256-cbc", $keyBytes, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $ivBytes);
echo($decrypt);

Categories

Resources