Ej DEV
Ej DEV

Reputation: 202

Encryption / Decryption PHP classes

What is the best encryption / decryption class / functions that can encrypt an array of data or objects and return it as a hash serialized string?

Then, on decryption, the serialized strings can be decrypted back to its original form of values containing objects or array values.

Thanks

Upvotes: 0

Views: 2221

Answers (2)

Emw
Emw

Reputation: 1665

The mcrypt library has a lot of functions to do encryption in as many ways as you can dream. Here's an example using AES:

$secretKey = 'the longer, the better';
$originalString = 'some text here';

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secretKey, $originalString,
                              MCRYPT_MODE_CBC, $iv);
printf( "Original string: %s\n", $originalString );
// Returns "Original string: some text here"

printf( "Encrypted string: %s\n", $crypttext );
// Returns "Encrypted string: <gibberish>"

$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secretKey, $crypttext,
                                MCRYPT_MODE_CBC, $iv);

// Drop nulls from end of string
$decrypttext = rtrim($decrypttext, "\0");

printf( "Decrypted string: %s\n", $decrypttext );
// Returns "Decrypted string: some text here"

Upvotes: 2

esqew
esqew

Reputation: 44699

Preface: You seem to have a notion that hashing some data would be the same thing as encrypting it. Hashing is NOT encryption and cannot be reversed with a password or keyfile, like encryption can.

PHP comes with several hashing protocols like md5 (md5_file), SHA1 (SHA1_file). It all really depends on what you're doing with this hash and what you're hashing in the first place.

Upvotes: 3

Related Questions