Reputation: 125
I am trying to encrypt the data using PHP and openssl command line, expected same encrypted data, but I am getting different data.
On linux, this is my openssl -version
OpenSSL> version
OpenSSL 1.0.2k-fips 26 Jan 2017
I tried to pass 48 bytes of data, hoping that might avoid padding. But no luck. I observed IVs are different so tried to use IV = 905E17D5F5E4939D0000000000000000 in PHP code also. But I got warning openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in
tried with/without -nosalt options on command line.
<?php
// encrypt/decrypt string
$output = false;
$encrypt_method = "AES-256-CBC";
$key = '905e17d5f5e4939d48bd04ff47f9de906375b87b67068b2ce5d1bbbbc8dca291';
$iv = '905e17d5f5e4939d';
$string = "123456789ABCDEFG123456789ABCDEFG123456789ABCDEFG";
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
echo $output;
?>
nEUDtXM7OQt32YEx778BgqZfocXrNNA9AihkioWZo9ri9p11DtxUpTFO30AHUk41F9PUBLu6YlYu/mdLcOZ3Cg==
where as openssl from linux command line:
echo "123456789ABCDEFG123456789ABCDEFG123456789ABCDEFG" |openssl enc -base64 -e -aes-256-cbc -K 905e17d5f5e4939d48bd04ff47f9de906375b87b67068b2ce5d1bbbbc8dca291 -iv 905e17d5f5e4939d -nosalt -p
key=905E17D5F5E4939D48BD04FF47F9DE906375B87B67068B2CE5D1BBBBC8DCA291
iv =905E17D5F5E4939D0000000000000000
c4JHI/8SIQkx7GXM2SclOXhbmR9vYBFLHt/jY0x7pJou9J2INJBQMISRYH4CPjvy
QDeyOWpcEEN/N6FnSdF0EA==
what am I missing here? how can I make sure both PHP and openssl -command line will use same IV/Key? How can make sure the padding is same in both if there is any? I want see same results on both sides.
Upvotes: 1
Views: 754
Reputation: 76
This works for me
<?php
// encrypt/decrypt string
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hex2bin('905E17D5F5E4939D48BD04FF47F9DE906375B87B67068B2CE5D1BBBBC8DCA291');
$iv = hex2bin('905E17D5F5E4939D0000000000000000');
$string = "123456789ABCDEFG123456789ABCDEFG123456789ABCDEFG";
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
echo $output;
?>
and in the CLI
echo -n "123456789ABCDEFG123456789ABCDEFG123456789ABCDEFG" |openssl aes-256-cbc -a -K 905e17d5f5e4939d48bd04ff47f9de906375b87b67068b2ce5d1bbbbc8dca291 -iv 905E17D5F5E4939D0000000000000000 -nosalt
The differences are
echo -n "foo"
instead of echo "foo"
(Otherwise you encrypt a different string ten in the PHP code).hex2bin()
.Upvotes: 6