Rocket
Rocket

Reputation: 1093

Encrypt / Decrypt AES-256-CBC String in PHP & BASH saving To/From MySQL?

I'm trying to work out how I can use openSSL to encrypt and decrypt a string in bash and PHP and get the same results regardless of where I do this.

I need to save the encrypted string to MySQL and retrieve it from MySQL to be read back and decrypted. I'm happy I can read and write from MySQL

For example. In PHP I can encrypt and decrypt using the following:

$textToEncrypt    = "Test Message";
$key              = "Testkey";
$iv               = "+ByrvYwA-4hB^?jF";
$keyHex           = bin2hex($key);
$ivHex            = bin2hex($iv);

//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, "AES-256-CBC", $key, 0, $iv);

//To Decrypt
$decryptedMessage = openssl_decrypt($encryptedMessage, "AES-256-CBC", $key, 0, $iv);

This can be decrypted in bash using:

echo -n "3GfrAdvtkHSpalmb4qzEVw==" | openssl aes-256-cbc -d -a -A -K "546573746b6579" -iv "2b427972765977412d3468425e3f6a46"

What I'm struggling with is encrypting the message in BASH so it can be decrypted back in PHP.

Can anyone advise on this ? Thanks

Upvotes: 1

Views: 914

Answers (1)

Bernhard
Bernhard

Reputation: 424

Just swap the openssl parameter. -d is for decryption, -e for encryption

echo -n "Test Message" | openssl aes-256-cbc -e -a -A -K "546573746b6579" -iv "2b427972765977412d3468425e3f6a46"

Upvotes: 1

Related Questions