I'm am trying to encrypt/decrypt some data using openssl_encrypt/openssl_decrypt. The purpose is as follows: the user enters some data in the GUI, this data is encrypted and stored at the database. Later it will be retrieved and decrypted only for a certain user profile.
The encrypt part is working fine since I've followed a colleague's advice, that is wrapping the output into a bin2hex function.
The whole point is I don't seem able to get a binary output when decrypting the data, even if I try to convert the output using hex2bin. I always get outputs like "� �Ps�1�_G�5�OUT".
I'm running out of ideas, actuallly I really don't know what to do at this point.
This is a sample code I've wrote to test this functions:
PHP
function encrypt($string) {
$cypher = 'aes-256-cbc';
$key = 's7aBkf4Ypn59bWviQziPDXyPasdaYlhQ';
$ivsize = openssl_cipher_iv_length($cypher);
$iv = openssl_random_pseudo_bytes($ivsize);
$encripted = openssl_encrypt(
$string, $cypher, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv
);
return $iv . $encripted;
}
function decrypt($string) {
$cypher = 'aes-256-cbc';
$key = 's7aBkf4Ypn59bWviQziPDXyPasdaYlhQ';
$ivsize = openssl_cipher_iv_length($cypher);
$iv = mb_substr($string, 0, $ivsize, '8bit');
$decrypted = mb_substr($string, $ivsize, null, '8bit');
$output = openssl_decrypt(
$decrypted, $cifrado, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv
);
return $output;
}
HTML:
<!doctype html>
<html>
<head><title>TEST</title></head>
<body>
<div style='margin-left:250px;'>
<form action="test.php" method="POST">
Encrypt
<input type="text" name="encrypt" value=''/>
<input type="submit" name="send" value='Send'/>
<br/><br/>
<?php
if (isset($_POST['encrypt']) && !empty($_POST['encrypt'])) {
echo 'encrypted string: ' . bin2hex(encrypt($_POST['encrypt']));
}
?>
<br/>
<br/>
Decrypt
<input type="text" name="decrypt" value=''/>
<input type="submit" name="send" value='Send'/>
<br/><br/>
<?php
if (isset($_POST['decrypt']) && !empty($_POST['decrypt'])) {
echo 'decrypted string: ' . decrypt($_POST['decrypt']);
var_dump(decrypt($_POST['decrypt']));
}
?>
</form>
</body>
Any ideas or help would be appreciated.
My PHP version is 5.4.45-0+deb7u2.
Thanks in advance.
OPENSSL_buf2hexstr
, but I don't know if pyOpenSSL provides it. I was recently talking to one of the devs about ab16
orhex
encoder for use withBIOs
. It makes sense to me because its a recurring request, and its a perfect fit for I/O consistency. If the library provided Base64 encoders and decoders, then it can provide Base32 and Base16 encoders and decoders, too.