I'm trying to send an encrypted json file to the mobile app.
I'm using RIJNDAEL_128 with MODE_CBC using PHP Mcrypt module; all works perfect on Server A ( Hostmetro provider ) but when i try the same script to Server B ( Hostgator provider ) the data encrypted can't be decrypted from mobile app.
I'm using the same key and the same IV ( the IV is set to 'zero' : \0 ).
I have checked the mcrypt version and it is the same on server A and B, only PHP version is different.
I test the script on my localhost and the json encrypt is changed again.
All my test say that if i try to encrypt a string like 'text' the result is the same everywhere, but if i try with a json the result is very different : where is the problem?
Thanks.
Update:
The code of the encrypt function is:
$str = $decrypted;
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
if (($pad = $block - (strlen($str) % $block)) < $block)
{
$str .= str_repeat(chr($pad), $pad);
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->the_key, $str, MCRYPT_MODE_CBC, $iv));
This is the code of the decrypt funciton:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->the_key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv);
# Strip PKCS7 padding.
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = ord($str[($len = strlen($str)) - 1]);
if ($pad && $pad < $block && preg_match(
'/' . chr($pad) . '{' . $pad . '}$/', $str))
{
return substr($str, 0, strlen($str) - $pad);
}
return $str;
UPDATE 08/12/2014
I have tested the generation of encrypted file and my localhost and my first server ( Hostmetro ) give me a valid file; only Hostgator create a "corrupted" file that can't be decrypted.
Try a base64_encode / decode before encryption / decription ..
Ok, i have found the problem: the problem is that when json_encode() try to encode an multidimensional array and not all the contents are cast to string when you encrypt this json object it can be decrypted by PHP in other server or the same but not by the mobile app.
THE SOLUTION
The solution is cast data into String, transform the array with json_encode(), encrypt the json with mcrypt : all is working now.
Related
I have given a task to integrate our company system to external system via API. When I read about the API, it stated that the data should be encrypted using MD5 and Triple Des Encryption, so I made some research about how to do it.
// Here's the credentials to be used for encryption.
$key = 'dEvu4MHkqz7mRgeqmB1mQEXi';
$iv = "avz9bUNx";
The data should be formatted as JSON String before encryption.
$params = array(
'Number' => '+11177109886' // example
);
$text = json_encode($params);
After that I made some codes to encrypt it.
function apiEncode($text, $key, $iv)
{
// to append string with trailing characters as for PKCS7 padding scheme
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$padding = $block - (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
return base64_encode($crypttext);
}
The error I got is.
Warning: mcrypt_encrypt(): Received initialization vector of size 0,
but size 32 is required for this encryption mode in
/Applications/XAMPP/xamppfiles/htdocs/dapsapi/rdremit.php on line 20
I have updated my php version to 7.1.
I had functions where i encrypt data using mcrypt.
Now this function is deprecated.
How can i decrypt the data anyway withoud going back to older versions of php.
This is the code i used:
public function encrypt($plaintext) {
$ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$ciphertext = mcrypt_encrypt(self::CIPHER, $this->key, $plaintext, self::MODE, $iv);
return base64_encode($iv.$ciphertext);
}
public function decrypt($ciphertext) {
$ciphertext = base64_decode($ciphertext);
$ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
if (strlen($ciphertext) < $ivSize) {
throw new Exception('Missing initialization vector');
}
$iv = substr($ciphertext, 0, $ivSize);
$ciphertext = substr($ciphertext, $ivSize);
$plaintext = mcrypt_decrypt(self::CIPHER, $this->key, $ciphertext, self::MODE, $iv);
return rtrim($plaintext, "\0");
}
With Constants:
const CIPHER = MCRYPT_RIJNDAEL_128; // Rijndael-128 is AES
const MODE = MCRYPT_MODE_CBC;
I saw that it was recommended to use OpenSSL. That is what i will use from now on. But how can i decrypt the older data using this method?
Thanks
Edit:
I know i can use OpenSSL as alternative.
Thats what i am doing for the content from now on.
But i need to decrypt my mcrypted code from my old contents.
*Edit request #symcbean
Tried to decrypt with OpenSSL like this:
public function decrypt($ciphertext) {
$ciphertext = base64_decode($ciphertext);
if (!function_exists("openssl_decrypt")) {
throw new Exception("aesDecrypt needs openssl php module.");
}
$key = $this->key;
$method = 'AES-256-CBC';
$ivSize = openssl_cipher_iv_length($method);
$iv = substr($ciphertext,0,$ivSize);
$data = substr($ciphertext,$ivSize);
$clear = openssl_decrypt ($data, $method, $key, 'OPENSSL_RAW_DATA'|'OPENSSL_ZERO_PADDING', $iv);
return $clear;
}
Important thing to note is that mcrypt_encrypt zero-pads input data if it's not a multiple of the blocksize. This leads to ambiguous results if the data itself has trailing zeroes.
openssl_decrypt doesn't remove the zero-padding automatically, so you're left only with the possibility of trimming the trailing nulls.
Here's a trivial example:
$data = "Lorem ipsum";
$key = "1234567890abcdef";
$iv = "1234567890abcdef";
$encrypted = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
echo bin2hex($encrypted) . "\n";
$decrypted = openssl_decrypt(
$encrypted, "AES-128-CBC", $key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
echo var_export($decrypted, true) . "\n";
$result = rtrim($decrypted, "\0");
echo var_export($result, true) . "\n";
Output:
70168f2d5751b3d3bf36b7e6b8ec5843
'Lorem ipsum' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . ''
'Lorem ipsum'
I solved it.
Don't know if its the right way (guess not)
But connected remotely on a server with a lower php version.
Decrypted all the content and encrypted with OpenSSL.
Thanks for the suggestions!
I also had some problems decrypting data encrypted with mcrypt_encrypt with openssl_decrypt. The following small test encrypts a string with mcrypt and openssl (with added zero padding and without) and decrypts all strings with both methods. This example uses ECB mode but you can easily change this to CBC by adding an IV if needed.
// Setup key and test data
$key = hash("sha256", 'test', true);
$data = 'Hello World';
$enc = $dec = [];
// Encrypt with MCRYPT_RIJNDAEL_128 method
$enc['RIJ'] = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB));
// Encrypt with OpenSSL equivalent AES-256
$enc['AES'] = base64_encode(openssl_encrypt($data, 'aes-256-ecb', $key, OPENSSL_RAW_DATA));
// Encrypt with OpenSSL equivalent AES-256 and added zero padding
if (strlen($data) % 8) $data = str_pad($data, strlen($data) + 8 - strlen($data) % 8, "\0");
$enc['AES0'] = base64_encode(openssl_encrypt($data, 'aes-256-ecb', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING));
// Decrypt all strings with MCRYPT_RIJNDAEL_128
$dec['mRIJ'] = bin2hex(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($enc['RIJ']), MCRYPT_MODE_ECB));
$dec['mAES'] = bin2hex(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($enc['AES']), MCRYPT_MODE_ECB));
$dec['mAES0'] = bin2hex(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($enc['AES0']), MCRYPT_MODE_ECB));
// Decrypt all strings with OpenSSL equivalent AES-256
$dec['oRIJ'] = bin2hex(openssl_decrypt(base64_decode($enc['RIJ']), 'aes-256-ecb', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING));
$dec['oAES'] = bin2hex(openssl_decrypt(base64_decode($enc['AES']), 'aes-256-ecb', $key, OPENSSL_RAW_DATA));
$dec['oAES0'] = bin2hex(openssl_decrypt(base64_decode($enc['AES0']), 'aes-256-ecb', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING));
// Print results
print_r($enc);
var_dump($dec);
The print_r and var_dump output is the following:
Array
(
[RIJ] => YcvcTwAMLUMBCZXu5XqoEw==
[AES] => +AXMBwkWlgM1YDieGgekSg==
[AES0] => YcvcTwAMLUMBCZXu5XqoEw==
)
array(6) {
["mRIJ"]=>
string(32) "48656c6c6f20576f726c640000000000"
["mAES"]=>
string(32) "48656c6c6f20576f726c640505050505"
["mAES0"]=>
string(32) "48656c6c6f20576f726c640000000000"
["oRIJ"]=>
string(32) "48656c6c6f20576f726c640000000000"
["oAES"]=>
string(22) "48656c6c6f20576f726c64"
["oAES0"]=>
string(32) "48656c6c6f20576f726c640000000000"
}
If you need the same encrypted string with the openssl methods as you had with mcrypt, you'll have add the zero padding manually to the string (AES0 in the example). This way you'll get the exact same encrypted and decrypted strings as before. For some additional information about the zero padding, you should look at Joe's answer here: php: mcrypt_encrypt to openssl_encrypt, and OPENSSL_ZERO_PADDING problems
If you don't want to manually add the zero padding to all new messages, you'll need different flags for decrypting the old mcrypt-encrypted messages and the new messages encrypted with openssl. For the old messages you'll have to use the OPENSSL_ZERO_PADDING flag ($dec['oRIJ'] in the example), whereas you must not use it for the openssl encrypted messages ($dec['oAES'] in the example). In my case I used this approach, because the default behaviour of openssl seems more correct to me as the mcrypt one - if you encrypt a string with 11 bytes you get a string with 11 bytes back after decrypting it. As you can see in the example, this is not the case with mcrypt or with openssl and the added zero padding. In these cases you would have to remove the trailing zeros manually to get the original data back.
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 .
I have a small problem with php mcrypt_decrypt function. Firstly, I use a 16-byte string, and encrypt it using mcrypt_encrypt; then, I use base64_encode, and put the output to mcrypt_decrypt, in order to get the initial string.
But the output is not what's expected. I checked that my base64 decoded string input for decoding is the exact output produced by mcrypt_decrypt. Here is my code:
//encrypt
$str="KKQT9W4st7vmdkps";
$key="43625A8C1E4330BDF84DDEE3DD105037";
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
$passcrypt=mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
echo $passcrypt;
That outputs PTfZ6Ephh8LTxXL4In33Og==. The decryption script is the following:
//decrypt
$str='PTfZ6Ephh8LTxXL4In33Og==';
$key='43625A8C1E4330BDF84DDEE3DD105037';
$str = base64_decode($str);
$str = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$str, MCRYPT_MODE_ECB,''),"\0");
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
echo $str;
And the output is not KKQT9W4st7vmdkps, but -nγ kk7Ζn’T instead. Any ideas? I'm using XAMPP and Apache server.
Thx guys for the feedback it was a silly mistake that i made...actually 'PTfZ6Ephh8LTxXL4In33Og==' was wrong in the decrypt function cause "I" was "l" in the end...so the decryption was not correct...but it was not my fault either since I was getting this string from a QR CODE scanner and both "I" and "l" are displayed the same...
For encryption, you need to:
1) Create an encryption resource
$str = "KKQT9W4st7vmdkps";
$key = "43625A8C1E4330BDF84DDEE3DD105037";
$r = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, '');
2) Randomly create encryption vector based on the size of $r
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($r),MCRYPT_RAND);
3) Initiliazing module using the resource,key and string vector
mcrypt_generic_init($r,$key,$iv);
4) Encrypt data/string using resource $r
$encrypted = mcrypt_generic($r,$str);
5) Encode it using base64_encode
$encoded = base64_encode($encrypted);
if(!mcrypt_generic_deinit($r) || !mcrypt_module_close($r))
$encoded = false;
6) Echoing it
echo 'Encrypted: '.$encoded;
For decryption, it's like a reverse process of encrypt
//Using the same enrypted string
$decoded = (string) base64_decode(trim($encoded));
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, '');
$ivs = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td,$key, $ivs);
$decoded = (string) trim(mdecrypt_generic($td, $decoded));
if(!mcrypt_generic_deinit($td) || !mcrypt_module_close($td))
$decoded = false;
Echoing it
echo 'Decrypted: '. $decoded;
Hope this helps. More info here.
I am working on some PHP code to perform AES string encryption and decryption. The encryption is working fine but I can't seem to decrypt it.
Below is the code that does the encryption and adds the required padding.
function encrypt($data)
{
$iv = "PRIVATE";
$key = CIPHERKEY;
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($data), MCRYPT_MODE_CBC, $iv));
}
function addpadding($string, $blocksize = 16)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
The code above is working fine the code below where it does the decryption keeps on failing. I try and do the decryption and then strip the padding but false is always returned from the padding function.
Below is the code that does the decryption and the stripping.
function strippadding($string)
{
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if(preg_match("/$slastc{".$slast."}/", $string)){
$string = substr($string, 0, strlen($string)-$slast);
return $string;
} else {
return "false";
}
}
function decrypt($data)
{
$iv = "PRIVATE";
$key = CIPHERKEY;
//$decoded = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$decrytped = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$base64Decoded = base64_decode($decrytped);
return strippadding($base64Decoded);
}
Thanks for any help you can provide.
In your decryption method, the decrypt and base64 steps are backwards. It's important that in whatever order you do your operations for encrypting, you do the reverse to decrypt.
In your encrypt method, you're base64 encoding the ciphertext:
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($data), MCRYPT_MODE_CBC, $iv));
When you decrypt, you need to undo the base64 encoding, and then decrypt that result.
$base64Decoded = base64_decode($data);
$decrytped = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $base64Decoded, MCRYPT_MODE_CBC, $iv);
Also, it looks like mcrypt will handle padding uneven blocks, so your addpadding() method might be superfluous.
You are using a too-short IV which is less than the blocksize. I assume this results in using a different IV on decryption. Blocksize is 16 bytes, so the IV should be 16 bytes, but your fixed-string IV is only 7 bytes (8 if you count the terminating zero byte which the underlying C code probably adds).
Instead of using a fixed string, you should be using a random IV generated by mcrypt_create_iv(). You can find out the length of one block by using mcrypt_get_iv_size() as shown in Example 1 in the mcrypt_create_iv() PHP manual. You would then send/store the random IV prepended to the ciphertext so you know what the IV was on decryption.
Also, mcrypt does its own padding, so you don't need to. And, as mfanto pointed out, you need to decode Base64 before decryption, not after.