Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Encrypt Data, Bash Decrypt it

I am trying to come up with a way to have PHP encrypt a file. I used to just use a PHP system call to run a script that encoded the file:

#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -salt -k $1 -in $2

Argument 1 was the password to use and argument 2 is the data. I then use a second script on a computer to de-crypt the file.

#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -d -salt -k $1 -in $2

This method of encrypting will not work on a production host as the PHP system call is disabled. I also would prefer not the change the decode function if at all possible.

Is there a way to replicate the above encrypt function using only PHP?

like image 567
kaptk2 Avatar asked Dec 28 '22 14:12

kaptk2


1 Answers

Take a look at mcyrpt_encrypt():

string mcrypt_encrypt ( string $cipher , string $key , string $data , 
                        string $mode [, string $iv ] )

Set $cipher to MCRYPT_RIJNDAEL_128 (AES-128), and $mode to MCRYPT_MODE_CBC.

Then use base64_encode() to generate a base-64 encoded output (ie: what the -a option does).


openssl derives the key and IV as follows:

Key = MD5(Password + Salt)
IV  = MD5(Key + Password + Salt)

Where Salt is a 8 byte salt. With this in mind, I created simple encrypt() and decrypt() routines:


function ssl_encrypt($pass, $data) {

    $salt = substr(md5(mt_rand(), true), 8);

    $key = md5($pass . $salt, true);
    $iv = md5($key . $pass . $salt, true);

    $ct = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $data, 
                          MCRYPT_MODE_CBC, $iv);

    return base64_encode('Salted__' . $salt . $ct);
}

function ssl_decrypt($pass, $data) {

    $data = base64_decode($data);
    $salt = substr($data, 8, 8);
    $ct = substr($data, 16);

    $key = md5($pass . $salt, true);
    $iv = md5($key . $pass . $salt, true);

    $pt = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $ct, 
                          MCRYPT_MODE_CBC, $iv);

    return $pt;
}

The parameter $data takes the string to be encrypted. If you want to encrypt a file, you'll have to get it via file_get_contents() or similar and then give that to the function.

Usage:

echo ssl_encrypt('super secret key', 'Hello World');

Generates something like (will change every time because of the random salt):

U2FsdGVkX18uygnq8bZYi6f62FzaeAnyB90U6v+Pyrk=
like image 184
NullUserException Avatar answered Jan 06 '23 02:01

NullUserException