PHP Encrypt/Decrypt with TripleDes, PKCS7, and ECB - php

I've got my encryption function working properly however I cannot figure out how to get the decrypt function to give proper output.
Here is my encrypt function:
function Encrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
Here is my decrypt function:
function Decrypt($data, $secret)
{
$text = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $secret, $text, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$pad = ord($data[($len = strlen($data)) - 1]);
return substr($data, 0, strlen($data) - $pad);
}
Right now I am using a key of test and I'm trying to encrypt 1234567. I get the base64 output from encryption I'm looking for, but when I go to decrypt it returns nothing (a blank area).
I'm not very well versed in encryption/decryption so any help is much appreciated!!

Thanks for anyone who took a look at my problem. I think I have solved it and here is my full solution. Hopefully it helps out someone else who is having a similar issue:
function Encrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
And here is the new decrypt function.
function Decrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
I had to add the same code for generating the key in the correct format before I ran the mycrypt_decrypt function.

Related

Why AES Decrypt code doesn't work in php 7.2

I used AES for encrypt the post parameters that send from java to server with volley. so I used below's class in my server for decrypt the post parammeters .
<?php
class MCrypt {
private $hex_iv = '31323334353637383930616263646566'; # converted Java byte code in to HEX and placed it here
private $key = '0FDOUZ.Qz'; #Same as in JAVA
function __construct() {
$this->key = hash('sha256', $this->key, true);
//echo $this->key.'<br/>';
}
function encrypt($str) {
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($encrypted);
}
function decrypt($code) {
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));
$str = mdecrypt_generic($td, base64_decode($code));
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $this->strippadding($str);
}
/*
For PKCS7 padding
*/
private function addpadding($string, $blocksize = 16) {
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
private 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 hexToStr($hex)
{
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
}
?>
Also I used below's code in newuser.php file .
<?php
.....
//decrypt
$encryption = new MCrypt();
$phone= $encryption->decrypt($phoneenc);
$password= $encryption->decrypt($passwordenc);
$serialdivice= $encryption->decrypt($serialdiviceenc);
$sequretyQustion= $encryption->decrypt($sequretyQustionenc);
$sequretyAnsewr= $encryption->decrypt($sequretyAnsewrenc);
.... ?>
Before Update php to php7.2 my code worked correctly . But for now It get error for decrypt method when I updated php . so How can i fix it?
I used openssl for both java and php .It's working correctly now.

I can encrypt data but cannot decrypt

I can successfully encrypt passed data but sadly cannot decrypt it. What is wrong with my decrypt() function? Maybe it is something with my Initialization Vector(iv). Here is my code:
function pad($data, $size) {
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
function unpad($data) {
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
//CORRECT ENCRYPTION METHOD
function encrypt($data) {
$key = "SiadajerSiadajer";
$iv_size = 16;
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
$encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
$joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
$encodedJoinedData = base64_encode($joinedData);
return $encodedJoinedData;
}
//WRONG DECRYPTION FUNCTION
function decrypt($encodedJoinedData){
$key = "SiadajerSiadajer";
$DecodedData = base64_decode($encodedJoinedData);
$size = strlen($DecodedData);
$cipheredsize = $size - 16;
$iv = substr($DecodedData, 0, 16);
$halfDecryptedData = substr($DecodedData, 16, $size);
$decryptedData = openssl_decrypt(unpad($halfDecryptedData, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
return $decryptedData;
}
$test = encrypt("sssss");
print $test;
$test2 = decrypt($test);
print $test2;
In the encrypt-method replace the line
$joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
with
$joinedData = $iv.$encryptedData;
because the conversions in the previous expression are unnecessary. This replacement doesn't change the result.
A possible solution for the decryption-part could be:
function decrypt($encodedJoinedData) {
$joinedData = base64_decode($encodedJoinedData);
$iv = substr($joinedData, 0, 16);
$encryptedData = substr($joinedData, 16);
$key = "SiadajerSiadajer";
$decryptedData = openssl_decrypt($encryptedData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
$unpaddedData = unpad($decryptedData);
return $unpaddedData;
}

Migration from mcrypt_encrypt() to openssl_encrypt()

I have forced to migrate from PHP 5.6 to 7.0+, everything is fine except the mcrypt_encrypt(), it was deprecated already as stated in php.net.
Here's my code
$json = array(
'Amount' => $amount
);
$data = json_encode($json);
function encrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
$data2 = utf8_encode($data);
$iv = utf8_encode("jvz8bUAx");
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'cbc');
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data2, MCRYPT_MODE_CBC, $iv);
return urlencode(base64_encode($encData));
}
I want to replace the deprecated lines with openssl_encrypt.
function encrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
$data = utf8_encode($data);
$iv = utf8_encode("jvz8bUAx");
$method = 'AES-256-CBC';
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv . $encrypted);
return $encrypted;
}
Error:
IV passed is only 8 bytes long, cipher expects an IV of precisely 16
bytes, padding with \0
What I am missing?
UPDATE: Adding decryption part
function decrypt($data, $secret)
{
//Generate a key from a hash
$data = urldecode($data);
$iv = utf8_encode("jvz8bUAx");
$key = md5(utf8_encode($secret), true);
// Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data3 = base64_decode($data);
return $data4 = mcrypt_decrypt('tripledes', $key, $data3, MCRYPT_MODE_CBC, $iv);
}
Updated
So what you are looking for is the des-ede3-cbc Openssl algorithm.
A convenient way to get a list of all your openssl algo's that are on your server is to run:
print_r(openssl_get_cipher_methods(TRUE));
This will generate a list that makes for a good reference.
It looks like there was a padding issue as well. Mcrypt adds padding during the encryption routine and the Openssl does not. So you have to add padding on the encryption side for the Openssl. We also need to force the no_padding in the openssl functions.
These functions should work for you now.
function encryptNew($data, $secret){
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
$data = utf8_encode($data);
$iv = utf8_encode("jvz8bUAx");
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8); //You key size has to be 192 bit for 3DES.
$method = 'des-ede3-cbc'; //<----Change you method to this...
//Mcrypt adds padding inside the function. Openssl does not. So we have to pad the data.
if (strlen($data) % 8) {
$data = str_pad($data, strlen($data) + 8 - strlen($data) % 8, "\0");
}
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); //Force zero padding.
$encrypted = urlencode(base64_encode($encrypted)); //Added the urlencode.....
return $encrypted;
}
function decryptNew($data, $secret){
//$data = base64_decode(urldecode($data));//<--If you have raw data coming in this needs to be commented out.
$iv = utf8_encode("jvz8bUAx");
$key = md5(utf8_encode($secret), true);
// Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$method = 'des-ede3-cbc';
return openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv); //Force zero padding.
}
Hope this helps.

Some Strings Won't Decrypt

I have a function to encrypt and decrypt a string with a salt/password, but there's an issue, I have no problem encrypting any string, but with decrpyting it has a problem decrypting some strings...
For example it will decrypt "Hello World", but not "Login" or "RedeemToken"... The code i'm using is below with some outputs and debugging stuff:
function encrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
function decrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
Also the functions above are used like this:
echo encrypt($string);
echo decrypt($string);
Example of some strings that encrypt, but will not encrypt:
Login - Doesn't Decrypt
RedeemToken - Doesn't Decrypt
Blacklist - Decrypt Works
Email - Decrypt Works
If anyone can point out the issue or help, please let me know, thanks!
HERE IS MY CODE:
USE - "http://example.com/test.php?st=xeJuD3+A0Po="
<?php
$string123 = mysql_escape_string($_GET["st"]);
echo decrypt($string123);
function encrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
function decrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
?>
Found ;)
In your URL, use http://example.com/test.php?st=xeJuD3%2BA0Po%3D as =+ and other char are not allowed tu be used in URL.
Take a look at http://php.net/manual/fr/function.rawurlencode.php to craft right URL from your base64 encrypted data
If you can't change the URL before it hit PHP, you'll have to change back the space in + :
$_GET['st'] = str_replace(' ', '+', $_GET['st']);
And BTW, remove the $string123 = mysql_escape_string($_GET["st"]); mysql_ is for mysql, nothing else, it's not a magic spell you cast everywhere. the only thing it does is change ' to \' and it wont help you anywhere; even in MySQL it's now depreciated and you need to use PDO or mysqli
for this :
<?php
function encrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
//Pad for PKCS7
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
//Encrypt data
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
function decrypt($data)
{
$secret = "FUSIONIDISTOPNOTCHCODEDBYMELTYNET";
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
echo "'". ($a = encrypt('Email'))."'<br>\n";
echo "'".decrypt($a)."'<br>\n";
echo "'".decrypt('AA/PpTmKWjY=')."'<br>\n";
echo "'".($e= encrypt('Login'))."'<br>\n";
echo "'".decrypt($e)."'<br>\n";
echo "'".decrypt('xeJuD3+A0Po=')."'<br>\n";
I get :
'AA/PpTmKWjY='
'Email'
'Email'
'xeJuD3+A0Po='
'Login'
'Login'
So, for me it work fine...

iOS/PHP kCCDecodeError

I can't for the life of me work out why when I encrypt something in PHP I can't then decrypt it in my iOS app, but PHP can decrypt iOS encrypted strings and decrypt/encrypt between itself.
PHP -> Obj-C FAILS.
Yes, I have looked across the net and the only solution I found was to use CBC in PHP which I'm already doing.
I'm using the FBEncryptor library for iOS and these are the encrypt/decrypt functions in PHP:
function encrypt($decrypted)
{
$iv = ''; for($i=0;$i<16;$i++){ $iv .= "\0";}
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $passKey, $decrypted, MCRYPT_MODE_CBC, $iv);
$ciphertext = base64_encode($ciphertext);
return $ciphertext;
}
function decrypt($encrypted)
{
$iv = ''; for($i=0;$i<16;$i++){ $iv .= "\0";}
$ciphertext = base64_decode($encrypted);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $passKey, $ciphertext, MCRYPT_MODE_CBC, $iv);
return $plaintext;
}
From the FBEncryptor Github page (emphasis mine):
Supported encryption algorithm is AES 256 bit only.
But in your code snippet above, you're doing:
mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
i.e. decrypting with AES 128 bit as your cipher.
You'll need to correct your code accordingly. Other common mistakes include using mismatched padding and block cipher operation modes.
I managed to work out the problem. Was a silly mistake on my part with the pass key variable. Here is my final implementation anyway for anyone else that comes across this problem:
function encrypt($decrypted)
{
$thePassKey = "12345678901234567890123456789012";
# Add PKCS7 padding.
$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, $thePassKey, $str, MCRYPT_MODE_CBC, $iv));
}
function decrypt($encrypted)
{
$thePassKey = "12345678901234567890123456789012";
$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, $thePassKey, 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;
}

Categories