Page 1 of 1

DES encryption, (php) mcrypt and (c#)

Posted: Fri Jun 11, 2010 11:17 am
by KeithB
I have a problem trying to encrypt a string in PHP and also in C# using DES (cbc) encryption. The problem I'm facing is that I'm getting different results using the different languages.

In PHP:

Code: Select all

$td = mcrypt_module_open('des', '', 'cbc', '');
mcrypt_generic_init($td, pack("H*", '0F26EF560F26EF56'), pack("H*", '0F26EF560F26EF56'));
$encryptedText = base64_encode(mcrypt_generic($td, 'My Secret Text'));
echo "Encrypted=".$encryptedText;
Results in

Code: Select all

Encrypted=HLp51qoFW0rimOTafCVTVQ==

In C#:

Code: Select all

SymmetricAlgorithm objCryptoService = (SymmetricAlgorithm)new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, objCryptoService.CreateEncryptor(StringToBytes.ConvertHex("0F26EF560F26EF56"), StringToBytes.ConvertHex("0F26EF560F26EF56")), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write("My Secret Text");
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
Response.Write("Encrypted=" + Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
 
 
Public static class StringToBytes
{
    public static byte[] ConvertHex(String sHexString)
    {
        int iCharCount = sHexString.Length;
        byte[] oBytes = new byte[iCharCount / 2];
        for (int i = 0; i < iCharCount; i += 2)
        {
            oBytes[i / 2] = Convert.ToByte(sHexString.Substring(i, 2), 16);
        }
 
        return oBytes;
    }
}
Results in

Code: Select all

Encrypted=HLp51qoFW0ojU8eGEGkk4w==

You can see that they are close...

PHP: HLp51qoFW0rimOTafCVTVQ==
C# : HLp51qoFW0ojU8eGEGkk4w==

But something is going wrong somewhere, I suspect it's a difference between (PHP) pack("H*", '0F26EF560F26EF56') and (C#) StringToBytes.ConvertHex("0F26EF560F26EF56") but I'm really struggling to spot it.

Any help would be greatly appreciated!!

Re: DES encryption, (php) mcrypt and (c#)

Posted: Fri Jun 11, 2010 2:15 pm
by KeithB
I found this little gem which gave me a solution TripleDES rather than DES but works consistently on both platforms nonetheless!

http://sanity-free.org/131/triple_des_b ... sharp.html

Hope that helps someone!