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.
2
Answers
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
With the following command:
note: please notice the use of
printf %s
instead ofecho
(which adds a newline at the end).You get:
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
:ASIDE: answering OP’s initial question.
For calling the
openssl
command in a pipe inside php you can useshell_exec
, but you SHALL prevent any potential code injection: