Page 1 of 1

TripleDESDecryptString From C# to PHP

Posted: Wed May 24, 2006 8:28 am
by sava
Hi

I'm tring to rewrite this function on PHP:

C# code:

Code: Select all

public string TripleDESDecryptString( string key, string base64Text) {

	string result = string.Empty;
	try {
		_DES.Key = _hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
		_DES.Mode = CipherMode.ECB;
		ICryptoTransform DESDecrypt = _DES.CreateDecryptor();
		byte[] Buffer = Convert.FromBase64String(base64Text);
		
		result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); 
	}
	
	catch( Exception) {
		result = string.Empty;
	}
	
	return result;
}
PHP Code:

Code: Select all

function  TripleDESDecryptString($key, $base64Encodedstring) {
	$td = mcrypt_module_open('tripledes', '', 'ecb', '');
		
	$Arr = str_split(md5($key,1));
	foreach ($Arr as $value) {
		$keyArr .= bin2hex($value);
	}
	$key = $keyArr;
	
	$iv_size = mcrypt_enc_get_iv_size($td);
	$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	
	mcrypt_generic_init($td, $key, $iv);
	
	return mdecrypt_generic($td, base64_decode($base64Encodedstring));
}
When i pass $base64Encodedstring to PHP it does not return correct answer.
I don't know why it does not work...

Maybe the problem is in the key format:

Code: Select all

_DES.Key = _hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
does not match:

Code: Select all

$Arr = str_split($key);
	$Arr = str_split(md5($key,1));
	foreach ($Arr as $value) {
		$keyArr .= bin2hex($value);
	}
	$key = $keyArr;
... any ideas ?

Posted: Sun May 28, 2006 6:13 am
by sava
.... ?

Posted: Sun May 28, 2006 6:15 am
by Soogn
Paste some results, and go further into the problem -- noone here is going to delve into crypto, we're mostly web developers -- on the other hand, cheack PEAR -- a module probably already exists, and quite a lot of PEAR modules can standalone

Posted: Sun May 28, 2006 9:51 am
by Ambush Commander
I suspect that you're right. Can you run a consistency check between the two hashes? I don't think bin2hex() is the correct way to go about things, but I'm not that well versed in binary, sorry.

Also, because of that MCRYPT_RAND you've got in the function body, I wouldn't expect the two's outputs to be the same. Try decrypting the PHP result string with C#, and vice versa.