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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KeithB
    New Member
    • Jun 2010
    • 2

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

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

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

    You can see that they are close...

    PHP: HLp51qoFW0rimOT afCVTVQ==
    C# : HLp51qoFW0ojU8e GEGkk4w==

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

    Any help would be greatly appreciated!!
  • KeithB
    New Member
    • Jun 2010
    • 2

    #2
    I found this little gem which gave me a solution TripleDES rather than DES but works consistently on both platforms nonetheless!



    Hope that helps someone!

    Comment

    Working...