Monday, March 28, 2011

c# 3des vs php

I came across the need to perform encryption, exchanging data generated by the php function from C #.

function encrypt($text)
{
$key = "qwertyuiopasdfghjklzxcvb";// 24 bit Key
$iv = "12345678";// 8 bit IV
$bit_check=8;// bit amount for diff algor.
$text_num =str_split($text,$bit_check);
$text_num = $bit_check-strlen($text_num[count($text_num)-1]);
for ($i=0;$i<$text_num; $i++) {$text = $text . chr($text_num);}
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES,'','cbc','');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mcrypt_generic($cipher,$text);
mcrypt_generic_deinit($cipher);
return base64_encode($decrypted);
}


How to decrypt in c #? Here's the solution:

public static string Decrypt(string text)
    {
      try
      {
        string key = "qwertyuiopasdfghjklzxcvb";// 24 bit Key
        string iv = "12345678";// 8 bit IV
        //int bit_check = 8;// bit amount for diff algor.
        ASCIIEncoding asc = new ASCIIEncoding();
        TripleDESCryptoServiceProvider p = new TripleDESCryptoServiceProvider();
        p.Mode = CipherMode.CBC;
        p.Key = Encoding.ASCII.GetBytes(key);
        p.IV = Encoding.ASCII.GetBytes(iv);
        p.Padding = PaddingMode.Zeros;
        ICryptoTransform c = p.CreateDecryptor();
        byte[] DataToDecrypt = Convert.FromBase64String(text);
        byte[] bDencrypted = c.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        return ASCIIEncoding.UTF8.GetString(bDencrypted);
      }


Note the use of PaddingMode Zeros  to solve offset problems. From both of these functions is easy now rebuilt their mirror functions.