I spent a couple of hours trying to figure it out, but I just can't get it to work. I have a c # encryption procedure that I need to map in php. I can’t change the C # version, this is not an option (the third party is solid in this).
Here's the C # code:
public static string ApiEncode(string data, string secret)
{
byte[] clear;
var encoding = new UTF8Encoding();
var md5 = new MD5CryptoServiceProvider();
byte[] key = md5.ComputeHash(encoding.GetBytes(secret));
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = key;
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.PKCS7;
byte[] input = encoding.GetBytes(data);
try { clear = des.CreateEncryptor().TransformFinalBlock(input, 0, input.Length); }
finally
{
des.Clear();
md5.Clear();
}
return Convert.ToBase64String(clear);
}
Here is the best I've come up with in PHP:
function apiEncode($data, $secret)
{
$key = md5(utf8_encode($secret), true);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ecb), MCRYPT_RAND);
$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = $blockSize - ($len % $blockSize);
$data .= str_repeat(chr($pad), $pad);
$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encData);
}
As far as I know, I am correctly handling the PKCS7 add-on on the PHP side. I'm not sure what else to try.
One note: C # happens on windows, and PHP on linux, not sure if this should matter.
Redth source
share