PHP openssl_encrypt tip


Recently I had to encrypt some data in PHP and send it to a Java App, the Java app was unable to decrypt the message.

I experimented with (data) padding, changing ciphers and changing the options for openssl_encrypt, but, none of those worked.

It was a requirement at the Java end for the Key to be hashed (sha256) and then used for encryption. The thing that worked for me was converting the hexed key to binary and using that.

<?php
$iv = 'aBCaDU9phtMwtNeV';
$key = 'B47C5126B42C9E192FAEAA5AA1892136';
$string ='testtesttesttest';

openssl_encrypt($string, "AES-256-CBC", hex2bin(hash('sha256', $key)), 0, $iv);
=> "E5vjBpIdWXo2NNuXkPzsEDVX6YVR3oFvHDwX+LohRsg="

# Bash
# >>> bin2hex('aBCaDU9phtMwtNeV')
# => "614243614455397068744d77744e6556"
# hash('sha256', 'B47C5126B42C9E192FAEAA5AA1892136')
# => "58754fcb239dfd17dfba62da3a57556980c69158d23dae6a1c24a174afeb676c"
printf %s "testtesttesttest" | openssl enc -e -aes-256-cbc -base64 -K 58754fcb239dfd17dfba62da3a57556980c69158d23dae6a1c24a174afeb676c -iv 614243614455397068744d77744e6556
E5vjBpIdWXo2NNuXkPzsEDVX6YVR3oFvHDwX+LohRsg=
,

Leave a Reply

Your email address will not be published. Required fields are marked *