Keith

Keith

  • 0
  • 9
  • 0

DES encryption (c#) and mcrypt (php)

Jun 11 2010 3:22 AM
I have a problem trying to encrypt a string in C# and also in PHP using DES (cbc) encryption. The problem I'm facing is that I'm getting different results using the different languages.

In C#:
 
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
 Encrypted=HLp51qoFW0ojU8eGEGkk4w==

In PHP:
 
$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
 Encrypted=HLp51qoFW0rimOTafCVTVQ==


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!!

Answers (2)