Data encrypted with phpseclib cannot be decrypted using openssl - php

I am using phpseclib to encode the contents of a json file using a random key as follows:
$plainkey = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$payload_plain = file_get_contents("file.json");
$cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
$cipher->setKeyLength(256);
$cipher->setKey($plainkey);
$cipher->setIV($iv);
$enc_payload = $cipher->encrypt($payload_plain);
At this point, $enc_payload contains the ciphertext, and calling $cipher->decode on it returns the plaintext, as expected. So far so good.
The problem arises when i write this encrypted data to a file and then try to decrypt it using openssl, using a command such as the one below:
openssl enc -d -aes-256-cbc -iv 17741abad138acc10ab340aaa7c4b790 -K d96ab4a30d73313d4c525844fce61d9f925e119cf178761b27ad0deab92a32bf -in encrypted.txt -out plain.txt
whereby the values for -iv and -K have been obtained by using bin2hex on the random byte values obtained in the script above.
Running that command gives me an error and plain.txt contains a half correct / half scrambled version of the original json string.
Error:
bad decrypt
13124:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:.\crypto\evp\evp_enc.c:323:
What am i missing? I am thinking maybe the part where i use bin2hex on the key / iv is incorrect, but I have tried using the byte strings directly without any success. How is this done normally? Or am i missing anything obvious?
Thanks

It worked fine for me. My code (adapted from yours):
<?php
include('Crypt/AES.php');
$plainkey = pack('H*', 'd96ab4a30d73313d4c525844fce61d9f925e119cf178761b27ad0deab92a32bf');
$iv = pack('H*', '17741abad138acc10ab340aaa7c4b790');
$payload_plain = file_get_contents('plaintext.txt');
$cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
$cipher->setKeyLength(256);
$cipher->setKey($plainkey);
$cipher->setIV($iv);
$enc_payload = $cipher->encrypt($payload_plain);
file_put_contents('ciphertext.txt', $enc_payload);
I decrypted with this:
openssl enc -d -aes-256-cbc -iv 17741abad138acc10ab340aaa7c4b790 -K d96ab4a30d73313d4c525844fce61d9f925e119cf178761b27ad0deab92a32bf -nosalt -p -in encrypted.txt -out plaintext.txt
The difference is that I have -p and -nosalt. -p just prints the keys out but maybe -nosalt is what you need.
Or maybe the problem is simpler than even this. In the code snippet you posted you're not echo'ing or saving the key / iv anywhere. Maybe you're not outputting the right values.
I got the OpenSSL parameters from http://phpseclib.sourceforge.net/interop.html#aes,p1openssl,p2phpseclib

Related

Piping output of one command to the input of another in php

I'm attempting to run a bash command in a php script. Unfortunately, because the command contains a pipe to another command, it doesn't seem to work as simple as writing the actual bash command into proc_open, popen, or shell_exec. I'm trying to use openssl to decrypt an encrypted password. I have the encrypted password in a database and after I retrieve it I need to echo the encrypted pw and pipe it to openssl. This is the exact command I need to run in its basic bash format:
echo $encryptedPassword | openssl enc -base64 -d -aes-256-cbc -salt -pass pass: password -pbkdf2
Where password is the password I have chosen to use as a salt to encrypt it in the beginning which I'm obviously not going to put in the forum. I've tried to use proc_open, popen, and shell_exec and none of the info I've found online seems to work. There's very little information online for chaining commands within php which leads me to believe this may not be possible and I may have to take another approach. It seems there is a php openssl plugin, however my company is trying to keep things as basic as possible without installing additional components. I also feel like this would be good information to know for other command chaining as there won't always be a plugin to use.
Any help would be greatly appreciated.
With the following command:
note: please notice the use of printf %s instead of echo (which adds a newline at the end).
printf %s 'stringPassword' |
openssl enc -base64 -aes-256-cbc -salt -pass pass:'password' -pbkdf2
You get:
U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=
For deciphering it you have to:
base64-decode the output of openssl.
Get the salt, which is bytes 9-16 of the base64-decoded string.
Derive a 48 bytes key using PBKDF2 with the given password, the salt and 10000 iterations of sha256 hashing (default of openssl -pbkdf2).
Get the encryption key (which is bytes 1-32) and the iv (which is bytes 33-48) from the derived key.
Get the ciphered text, which is bytes 17 through the end of the base64-decoded string.
Decrypt the ciphered text using aes-256-cbc, the encryption key and the iv.
Now, let's try to decipher it with php:
function decrypt($data, $passphrase) {
$d = unpack(
'x8/a8salt/a*data',
base64_decode( $data, true )
);
$k = unpack(
'a32key/a16iv',
openssl_pbkdf2( $passphrase, $d['salt'], 48, 10000, 'sha256' )
);
return openssl_decrypt(
$d['data'],
'aes-256-cbc',
$k['key'],
OPENSSL_RAW_DATA,
$k['iv']
);
}
var_dump( decrypt('U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=', 'password') );
string(14) "stringPassword"
ASIDE: answering OP's initial question.
For calling the openssl command in a pipe inside php you can use shell_exec, but you SHALL prevent any potential code injection:
$cypher = 'U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=';
$secret = 'password';
$text = shell_exec(
'echo ' . escapeshellarg($cypher) . ' | ' .
'openssl enc -d -base64 -aes-256-cbc -salt -pbkdf2 -pass pass:' . escapeshellarg($secret)
);
################
var_dump($text);
string(14) "stringPassword"
It turns out the digest algorithm for openssl changed between versions. 1.0.2 and older used md5 as the digest. Anything newer than that uses sha256. Since I was encrypting with newer openssl but decrypting with an older openssl, on the decryption side with openssl I had to specify to use sha256 with the option -md sha256. Otherwise it would try to use the older md5 digest. A very helpful link that led me to this conclusion: https://bbs.archlinux.org/viewtopic.php?id=225863

How to decrypt a file in PHP that was encrypted in bash script with Openssl

I have to decrypt a file in my Laravel backend with PHP's openssl_decrypt.
The file is encrypted outside Laravel fro ma BASH script and openssl 1.1.
I looked at some explanations that would help me but found nothing that worked.
My openssl versions are the same (1.1) for both PHP and the server.
I tried many combinations of options but nothing worked.
Here is my BASH encrypting script:
APP_KEY='**************'
FILES_PATH='****/app/files/'
# We're looking for ".decrypted" files, which gonna be encrypted next
FILES_LIST=$(find $FILES_PATH -type f -name '*.decrypted' )
# We base64-decode the key then display it as Hex. string
KEY=$(echo $APP_KEY | base64 -d -i | xxd -p -c 64)
# For each file to encrypt :
while read -r file; do
# If there is actually a file :
if [ ! -z "$file" ]; then
output=${file%.decrypted}
chunkspath="${output}.chunk."
chunksname="${chunkspath##*/}*"
# We have to split the files into 32M. chunks because our server can't decrypt big files without memory leaks in php.
split -b 32M -d $file -a 3 $chunkspath
chunkslist=$(find $FILES_PATH -type f -name $chunksname)
touch $output
# For each chunk :
while read -r chunk; do
# Generate a random IV of 16 bytes (output is 32 characters in Hex.)
iv=$(openssl rand -hex 16)
temp="${chunk}.enc"
openssl AES-256-CBC -K $KEY -iv $iv -in $chunk -out $temp
# We prefix each chunk with his IV to let the server retrieve it when decrypting. See the PHP code bellow.
echo -n $iv >> $output
# Then we append each IV+Chunk in the final output file.
cat $temp >> $output
rm $temp $chunk
done < <(echo "${chunkslist}")
# I commented the next line to let me run some tests but the original file will have to be removed eventually.
# rm $file
fi
done < <(echo "${FILES_LIST}")
echo 'Done'
And here's my PHP's script for decrypting the file:
// This function is inside a Laravel's stream download response
function () use ($file, $log) { // $file is the Laravel model representation of a stored file.
$cipher = 'AES-256-CBC';
$key = base64_decode(substr(config('app.key'), 7));
$ivLen = 32; // Actually 16 bytes but 32 characters in hex format
$chunckLen = 32 * 1024 * 1024; // Chunks are 32Mo long or less for the last one
$fpIn = fopen(Storage::disk('files')->path($file->path), 'rb');
while (!feof($fpIn)) {
// IV and Key must be in binary format
$iv = hex2bin(fread($fpIn, $ivLen));
// We read the file chunks by chunks, decrypt it and print it.
$encrypted = fread($fpIn, $chunckLen);
$decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv);
while ($msg = openssl_error_string()) {
print $msg . "\n";
}
print($decrypted);
}
}
I expect the decrypted file to be readable.
With the code above, the output file contains this line: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
I tried with the OPENSSL_ZERO_PADDING options on the openssl_decrypt() method. The output file then contains binary data but the file is not readable (I guess the ecryption did not work as expected).
I also tried to set the -nopad option in the bash script but then this error is thrown: 4960:error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:data not multiple of block length:../openssl-1.1.1c/crypto/evp/evp_enc.c:425:.
Does someone know what there errors mean ? What did I do wrong ? I'm almost sure I missed something (I'm kind of new in the encryption world...)
Thank you!
Actually I just realized that the Key used in the script and the one used in Laravel weren't the same... Stupid me.
The code above is therefore correct and resolves my problem.

Convert openssl command to php

i have line of command
echo -n 2bRePass1234 | openssl dgst -sha1 -binary | openssl enc -base64
output : 3O3bhZbGKheK+g/M4pp18AwGqq8= (28 char)
i need to convert it php
what i tried. openssl_encrypt need $iv and $key. i just use random_bytes because dont know whats is the default value like the command above
return base64_encode(
openssl_encrypt(
sha1('testPass1234'),
'AES-128-CBC',
random_bytes(16),
OPENSSL_RAW_DATA,
random_bytes(16)
)
);
But its doest return same result as the command did.. is there any way just use default key and cipher to generate it?
Note: i put random_bytes(16) because i dont know what to fill it based on the command.
Two things ...
You are doing a dgst (digest) in your first call of openssl therefore you cannot call openssl_encrypt in your php.
By doing a digest you does not need random bytes.
There are at least 2 ways to do it in php
1) Using sha1 function
php -r "var_dump(base64_encode(pack('H*', sha1('testPass1234'))));"
string(28) "wW+fqYWyUoXq+c76j0j2mnD5Oyc="
2) Using openssl_digest function
php -r "var_dump(base64_encode(pack('H*', openssl_digest('testPass1234', 'SHA1'))));"
string(28) "wW+fqYWyUoXq+c76j0j2mnD5Oyc="
They will both return the same. The string returned from sha1 will be packed into a string of real bits and not treated as string.
PS: I saw you passed a different string in the command line sample and the php sample, but whenever passing the same string the results will be the same.
echo -n testPass1234 | openssl dgst -sha1 -binary | openssl enc -base64
wW+fqYWyUoXq+c76j0j2mnD5Oyc=
Hope it's what you whore looking for. Cheers!

openssl_decrypt for aes-128-cbc not working

I am working on decrypting some content coming from an API. They have provided a command as well. So with some mofication below is the command, which works perfectly fine:
openssl enc -d -aes-128-cbc -K 422943374a3568755d7c527f6e472132 -iv 00000000000000000000000000000000 -nopad -in <(echo 'D5fiXKI4ie4c69gcCwM4/p414yrYtH9np+piNoqZASbkUnHAvbB4norHz6d6uzJmIg1sULhHFmfQTkvpw0tIEVmNcjyP6j2LK8zXYzohtNlsqBHx5v4xHEIyCcvfbMJddd5hs97jqkUtHuQyer2GdfDKZseaGgpXJ75GK7uKFPkbJ3wgQ6A0Q7q2tbBYeXEDmRMO6OhWeHgrezQOcyjcdOQk50SjMuaSb9IRimwagXamiXRg0LyTzA18a0SuqtbKCNgXnmhf39YxJUudkRmcMQ==' | base64 --decode)
I need to code in PHP, so I need to translate same thing in PHP, and here is what I have written in PHP:
$encodedStr = "PYroeIibeYwy/waD3opLw6yWT6Wfv3AhBKhQpoR+6qT9gx/bTDdR9QIfXcVURoQ2QlTl8L+JZX4Ije8M+FAQOxVmEXAmyUpzLgeg7aRCA6iiJbav/W3xW0BWb3D3QELjKTN4KRB2FdM7G5eIIfvjpeySLxQ3h7eL16nQf+1rms4VoVsBaeO8aU+Zy9saKZR4oL+k40m6tjtvtXryg7sWcmUgdonP/Jg4osESrY3MmGl7qXSpJC+v4g3iOY7s8NwywSN9q2Id7P0IaVtb5AFOEQ==";
$secretHash = ",MF-,2Y*s8DoYCFI";
$encryptionMethod = "AES-128-CBC";
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$encrypted = base64_decode($encodedStr);
$hexKey = strToHex($secretHash);
$response = openssl_decrypt($encodedStr, $encryptionMethod, $hexKey, OPENSSL_ZERO_PADDING, $iv);
And in response, I am getting a string of odd characters instead of actual string which I can get from openssl command in command line.
As per openssl_decrypt documentation:
Takes a raw or base64 encoded string and decrypts it using a given method and key.
I have also tried giving base64 decoded value as well in first argument of this function. Encryption method also seems fine. And Zero padding as told in API document. Only thing which I think can be doubtful is zero iv. Let me know if I am making zero iv in wrong way. I have tried not using iv as well but not useful. Or also let me know if I am doing wrong in something else.
openssl_decrypt expects key to be binary not hex. You don't need to convert $secretHash to hex and just pass it as is.
$response = openssl_decrypt($encodedStr, $encryptionMethod, $secretHash, OPENSSL_ZERO_PADDING, $iv);

AES encrypt in Terminal and decrypt in PHP

I have come accross other threads with similar questions but due to recent changes in PHP (ie. mcrypt removal), I am seeking some advice as to how I'd best go about this using OpenSSL in 2017/18.
Using echo 'this string will be encrypted' | openssl enc -aes-256-cbc -a -pass pass:123 in the Mac Terminal, I was able to password encrypt the string and would now like to pass this (as a parameter) into a server-side PHP function to decrypt.
Having studied this question, I can see that it is possible but it uses the now removed mcrypt function. Further reading in the PHP manual, I am no closer to figuring out how to reverse this encryption command into its PHP decryption equivalent.
This recent answer is what I have implemented so far, yet again, it just won't work with a Terminal generated encryption, only one which was created in PHP (not shown here).
<?php
$encrypted_string = $_GET['data'];
$password = '123';
$decrypted_data = openssl_decrypt($encrypted_string, "AES-256-CBC", $password);
print "Decrypted Data: <$decrypted_data>\n";
?>
The OpenSSL PHP manual states that either plain text or base64 encoded strings can be passed in and be decrypted. As I have used the -a flag during encryption, I would expect base64 to be passed in, thus eliminating the source as a potential reason why no decrypted data is returned.
I have taken care of URL encoding such that any + symbols produced by the encryption algorithm are replaced with their - %2B - URL-Safe equivalent as they would otherwise be turned into a space character, thus breaking the parameter string. This further ensures that the encoded input string is correctly addressed by the decryption algorithm.
Questions: Why won't my PHP function decrypt the string generated by the terminal command, although both use the same method and password? What is missing from my PHP code that would enable this to work?
Cheers everyone.
UPDATE
I am now using Terminal command:
echo 'blah' | openssl enc -aes-256-cbc -a -K B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF -iv 64299685b2cc8da5
which encrypts to: Y4xelTtEJPUHytB5ARwUHQ==
I pass this to PHP using www.example.com/?data=Y4xelTtEJPUHytB5ARwUHQ==
PHP should take data param and decrypt. Currently, that function looks like this:
<?php
$encrypted_string = base64_decode($_GET['data']);
$key = 'B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF';
$iv = '64299685b2cc8da5';
$output = openssl_decrypt($encrypted_string, 'AES-256-CBC', hex2bin($key), OPENSSL_RAW_DATA, hex2bin($iv));
print "Decrypted Data: <$output>\n";
?>
OpenSSL uses a proprietary KDF that you probably don't want to put the effort in to reproduce in PHP code. However, you can pass your key as pure hex instead, avoiding the KDF, by using the -K flag:
echo 'blah' | openssl enc -aes-256-cbc -K 0000000000000000000000000000000000000000000000000000000000000000
Here, the large hex string is your 256-bit key, hex encoded. This encryption operation will be compatible with your PHP.

Categories