PHP AES 256 encrypt weird characters - php

I have the following encrypt code:
function encryptData($value){
$key = "7685647tfyr65413285746352413sgfh";
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
return $crypttext;
}
echo 'Encrpt: ' . encryptData('This is just a test');
The output is: Encrpt: yUB�F3�*ľ�G-�ۅd�8�f�_�X/O
I'm going to place this into a mySQL database but was unsure if it would accept those types of weird characters?
Am i doing this correctly?

Yes, you are doing it correctly, however the output is a binary value. To be save, it's good practice to encode it to a 'regular' string via
$encrypted_base64 = base64_encode($crypttext);
Just remember to do the opposite before decoding;
$crypttext = base64_decode($encrypted_base64);

Related

Encryption and Decryption for Triple DES in PHP Example in ECB Mode

Can you please give me a full example of how to create an encryption and decryption in PHP language? I use hexa for the data and the key. I search through google and find that there is one website that match my expectation which is here.
Take this for example:
Data: 225551100012FFFF
Key: DC1C1F2B180F85D8D522A75D2354ED149A5B81F198387B51
When I decrypt, I got 389da227862957c4
Thank you in advance!
Have found my answer from this website http://www.isapp.it/en/menu-en/31-tips-a-tricks/php/118-php-how-to-encrypt-text-in-triple-des-ecb.html
But because i want to encrypt and decrypt it using hexa, i modify the code a bit to this
function cryptECB($crypt, $key) {
//Omit hex2bin and bin2hex if plain text is used
$crypt = hex2bin($crypt);
$key = hex2bin($key);
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$cryptText = mcrypt_encrypt(MCRYPT_3DES, $key, $crypt, MCRYPT_MODE_ECB, $iv);
return bin2hex($cryptText);
}
function decryptECB($encrypted, $key) {
//Omit hex2bin and bin2hex if plain text is used
$encrypted = hex2bin($encrypted);
$key = hex2bin($key);
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$stringText = mcrypt_decrypt(MCRYPT_3DES, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
return bin2hex($stringText);
}

How to Encrypt-Decrypt .pdf, .docx files in php?

I am trying to encrypt/decrypt files in PHP. So far I am successful with .txt files but when it comes to .pdf and .doc or .docx my code fails, i.e. it gives absurd results. Can anyone suggest modification/alternative in my code? Thanks in advance!
Here's the encryption function
function encryptData($value)
{
$key = "Mary has one cat";
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB, $iv);
return $crypttext;
}
Here's the decryption function
function decryptData($value)
{
$key = "Mary has one cat";
$crypttext = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
I used this blog to help me encrypt/decrypt pdf files on my local machine using openssl_encrypt because mcrypt is deprecated in php7.
First, you get the file contents of the pdf:
$msg = file_get_contents('example.pdf');
Then I called the encryption function written in the blog post:
$msg_encrypted = my_encrypt($msg, $key);
Then I open the file I want to write to and write the new encrypted msg:
$file = fopen('example.pdf', 'wb');
fwrite($file, $msg_encrypted);
fclose($file);
For reference, in case that blog goes down, here are the encryption and decryption functions from the blog:
$key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';
function my_encrypt($data, $key) {
// Remove the base64 encoding from our key
$encryption_key = base64_decode($key);
// Generate an initialization vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
// Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
// The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
return base64_encode($encrypted . '::' . $iv);
}
function my_decrypt($data, $key) {
// Remove the base64 encoding from our key
$encryption_key = base64_decode($key);
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
}

PHP sending encrypted data via the URL

I'm trying to send encrypted data over the url to another site (using file_get_contents("anotherUrl.php?hash=$encryptedString"). The problem is, sometimes, the encryption contains some special characters, like +, and this causes the decryption to fail.
Here are my encryption / decryption methods:
public function encrypt($string, $key)
{
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}
public function decrypt($encrypted, $key)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
}
Here's an example encrypted string which contains a +, and I'm guessing that this causes the decryption to fail.
oWCrVPaS+5GbxcQFc0fulUk/zRAkDD60av4zlPiWskE=
Any ideas how I should solve this? I've tried to do urlencode() and urldecode() on the hash, however that also seems to cause the encryption to break. Is there a way to change the encryption algorithm to get it to only return url safe characters?
Take a look at this thread:
Passing base64 encoded strings in URL
Essentially you DO want to urlencode() before sending the string, however you do NOT want to urldecode() at the other end.
In order to solve this problem I now use the following (after 3 hours of pain), and it works great.
Feel free to copy and paste
function encrypt($pure_string) {
$dirty = array("+", "/", "=");
$clean = array("_PLUS_", "_SLASH_", "_EQUALS_");
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$_SESSION['iv'] = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $_SESSION['encryption-key'], utf8_encode($pure_string), MCRYPT_MODE_ECB, $_SESSION['iv']);
$encrypted_string = base64_encode($encrypted_string);
return str_replace($dirty, $clean, $encrypted_string);
}
function decrypt($encrypted_string) {
$dirty = array("+", "/", "=");
$clean = array("_PLUS_", "_SLASH_", "_EQUALS_");
$string = base64_decode(str_replace($clean, $dirty, $encrypted_string));
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $_SESSION['encryption-key'],$string, MCRYPT_MODE_ECB, $_SESSION['iv']);
return $decrypted_string;
}
Instead of using Base64 for encoding your data you can also use Base32 (RFC 4648) which is URL-safe because it only uses letters A–Z (case-insensitive) and the digits 2–7. There is already a PHP library for encoding/decoding. Note that Base32 takes ~20% more space than Base64.
You can also use URLcrypt which is a handy library helping you with encryption and Base32 encoding.
class Encryption {
var $skey = "SuPerEncKey2010"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}

SHA1 the PHP mcrypt_decrypt result

I have 2 encrypt & decrypt functions using PHP mcrypt library.
public function encrypt_string($input, $key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_CBC, $iv);
return base64_encode($iv . $cipher);
}
public function decrypt_string($input, $key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$ciphertext = base64_decode($input);
$iv = substr($ciphertext, 0, $iv_size);
$cipher = substr($ciphertext, $iv_size);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipher, MCRYPT_MODE_CBC, $iv);
}
Given that the key is generated by:
$key = pack('H*', 'dfgsdighsdfksdhfosdfasdjldsfsdfgdfkgdl'); // a random key
I can successfully obtain back the input after encryption & decryption.
Here is the code:
$pass = '123456';
echo sha1($pass) . PHP_EOL; // prints 7c4a8d09ca3762af61e59520943dc26494f8941b
$pass_cipher = encrypt_string($pass, $key);
$pass_decrypt = decrypt_string($pass_cipher, $key);
echo $pass_decrypt . PHP_EOL; // prints 123456
echo sha1($pass_decrypt) . PHP_EOL; // prints f41b44dbecccaccfbb4ccf6a7fc4921c03878c6d
However, the SHA1 result is different:
7c4a8d09ca3762af61e59520943dc26494f8941b // before encrypt & decrypt
f41b44dbecccaccfbb4ccf6a7fc4921c03878c6d // after encrypt & decrypt
Why is it different ? What did I miss ?
UPDATE:
The accepted answer is useful. For people who wants additional information, here it is:
echo bin2hex($pass) . PHP_EOL; // prints 313233343536
echo bin2hex($pass_decrypt) . PHP_EOL; // prints 31323334353600000000000000000000
and after trim(), the SHA1 result works as expected, as empty hidden 0 are removed.
Problem is that your decrypt_string returns 16 bytes string, that is filled with 0 bytes at the right side. It's a problem known for about 2 years.
Remove null bytes from the right with line similar to this one:
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipher, MCRYPT_MODE_CBC, $iv), "\0");
Be careful not to encrypt things with null character at the end, as cryptology functions in PHP works as if all strings were null-terminated and are not shy to cut string at first \0 or to return a bit of \0s glued to the end of their output.
in post encrypted data + sign will be replaced with whitespace. thats why decryption was not done .

Blowfish encryption in php

I'm writing an encryption to my application and website, but I don't know how to correctly encrypt the string in php. Decryption is already done by this code:
function decrypt_blowfish($data,$key){
$iv=pack("H*" , substr($data,0,16));
$key=pack("H*" , $key);
$x =pack("H*" , substr($data,16));
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
return $res;
}
I tried with simple:
function encrypt_blowfish($data,$key){
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
return $crypttext;
}
But it returns strang ASCI chars instead of correct blowfish code. Could somebody explain me why, and what am I doing wrong?
Thanks in advance
C.H.
function decrypt_blowfish($data,$key){
$iv=pack("H*" , substr($data,0,16));
$x =pack("H*" , substr($data,16));
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
return $res;
}
function encrypt_blowfish($data,$key){
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
return bin2hex($iv . $crypttext);
}
$string = encrypt_blowfish('hello world', 'abc123');
echo 'ENCRYPTED: ' . $string . "\n";
echo 'DECRYPTED: ' . decrypt_blowfish($string, 'abc123');
Try that. In the decryption function you are converting from hex to binary, so it is expecting a hex value to be passed. Your encryption function is outputting binary, so you need to convert it to hex with the above change.

Categories