Niko Roberts' Blog

Travel Addict and Web and Desktop Developer

PHP mcrypt and C# Encryptor

For the past day I have been looking for a solution to transfer encrypted information between a PHP web application and a C# desktop application.

This requires that both systems use the same algorithm, key and init vector (IV)

This isn't as easy as it sounds. The slightest difference in the setup of either system means that the encrypted information cannot be decoded on the other end and makes it basically useless.

(The following PHP code has been modified after some useful debugging and comments from Serge N.)

 



//Encryption function
function mc_encrypt($encrypt, $key, $iv)
{
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    mcrypt_generic_init($td, $key, $iv);
    $encrypted = mcrypt_generic($td, $encrypt);
    $encode = base64_encode($encrypted);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $encode;
}


//Decryption function
function mc_decrypt($decrypt, $key, $iv)
{
    $decoded = base64_decode($decrypt);
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    mcrypt_generic_init($td, $key, $iv);
    $decrypted = mdecrypt_generic($td, $decoded);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return trim($decrypted);
}


 


//Usage in PHP
$original = "original message";
$key = "abcdefg_abcdefg_abcdefg_abcdefg_";
$iv = "abcdefg_abcdefg_";
$keysize = 128;


$enced = mc_encrypt(stripslashes($original), $key, $iv);
echo "Encrypted:<br>".$enced."<br>";
$unced = mc_decrypt($enced, $key, $iv);
echo "Decrypted:<br>".$unced."<br>"; 


That is the PHP code done. We can generate a key and then at any point use the decrypt function to unencode it.

Now the trick is getting the exact same functionality in .NET (with C#) 

I found that the class below does it pretty well (this uses the default Rijndael algorithm which is 128 in C#)



public static class Encrypter
{
          public static String EncryptIt(String s, byte[] key, byte[] IV)
          {


             String result;
              RijndaelManaged rijn = new RijndaelManaged();
              rijn.Mode = CipherMode.ECB;
              rijn.Padding = PaddingMode.Zeros;
              using (MemoryStream msEncrypt = new MemoryStream())
              {
                  using (ICryptoTransform encryptor = rijn.CreateEncryptor(key, IV))
                  {
                      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                     {
                         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                         {


                             swEncrypt.Write(s);
                          }
                      }
                  }
                  result = Convert.ToBase64String(msEncrypt.ToArray());
              }
              rijn.Clear();
              return result;
          }
          public static String DecryptIt(String s, byte[] key, byte[] IV)
          {
              String result;
              RijndaelManaged rijn = new RijndaelManaged();
              rijn.Mode = CipherMode.ECB;
              rijn.Padding = PaddingMode.Zeros;
              using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(s)))
              {
                  using (ICryptoTransform decryptor = rijn.CreateDecryptor(key, IV))
                  {
                      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                      {
                          using (StreamReader swDecrypt = new StreamReader(csDecrypt))
                          {
                              result = swDecrypt.ReadToEnd();
                          }
                      }
                  }
              }
              rijn.Clear();
              return result;
          }
}

//Usage


Encoding byteEncoder = Encoding.UTF8;
byte[] rijnKey = byteEncoder.GetBytes("abcdefg_abcdefg_abcdefg_abcdefg_");
byte[] rijnIV = byteEncoder.GetBytes("abcdefg_abcdefg_");


String message = "original message";
String encrypted = Encrypter.EncryptIt(message, rijnKey, rijnIV);
String decrypted = Encrypter.DecryptIt(encryption, rijnKey, rijnIV);


Console.WriteLine("Original: "+message);
Console.WriteLine("Encrypted: "+encrypted);
Console.WriteLine("Decrypted: "+decrypted);


I hope this shortens someone's search process when trying to do this.

PS. Yes this is my first try at using the [ code ]  containers in Posterous (not the easiest thing in the world but after some tweaking eventually got the code to appear here nicely)

Posted

JW Player with Seeking with MP4 videos

I have just been working on getting JW Player working with seeking (so you can click somewhere in the video and go directly to it)

I managed to get it using psstream (PHP module) and H624 Streaming Module for Apache

Pretty simple process once you figure out what all the components are... (which is why I am listing them here - these are a instructions for non-commercial use)

I am running Ubuntu 8.04 with Apache/2.2.8 and PHP 5.2.4

PSStream

(as I am writing this I realise that the developer of psstream has discontinued development on psstream and has a new module called Loomiere Stream written in C that increases the performance of the module by approx. 6 times, this however is not publically available yet)

wget http://codeblog.palos.ro/downloads/psstream-1.0.tar.gztar -xvzf psstream-1.0.tar.gzcd psstreamphpize./configure --enable-psstreammakesudo make installsudo cp psstream.ini /etc/php5/conf.dsudo /etc/init.d/apache2 restartcp psstream.php /var/www/mywebsitedirectory/

H264

sudo apt-get install apache2-threaded-devcd ~wget http://h264.code-shop.com/download/apache_mod_h264_streaming-2.2.7.tar.gztar -zxvf apache_mod_h264_streaming-2.2.7.tar.gzcd ~/mod_h264_streaming-2.2.7./configure --with-apxs=`which apxs2makesudo make installsudo nano /etc/apache2/apache2.conf

Then add the following lines to the configuration (for all websites served off apache)

LoadModule h264_streaming_module /usr/lib/apache2/modules/mod_h264_streaming.soAddHandler h264-streaming.extensions .mp4

Then restart apache

sudo /etc/init.d/apache2 restart 

JWPlayer

JW Player is just installed on each page you want a video playing on, using Javascript

When you download the JW Player you should get a set of js and swf files if you include these in your HTML code

In the HEAD section

<script type="text/javascript" src="jwplayer/swfobject.js"></script>

In the BODY section

<div id='mediaspace'> </div><script type='text/javascript'>        var so = new SWFObject('/jwplayer/player.swf','mpl','470','320','9');        so.addParam("flashvars","image=videos/MyVideoFirstFrame.png&file=http://www.mydomain.com/psstream.php&type=video&id=videos/MyVideo.mp4&streamer=lighttpd");        so.addParam('allowfullscreen','true');        so.addParam('allowscriptaccess','always');        so.addParam('wmode','opaque');        so.addVariable('file','/videos/MyVideo.mp4');        so.write('mediaspace');</script> 

Well I think that is all for now. Pretty simple and straight forward, I will try and fix any mistakes if I find them.

Enjoy,

Niko

 

A working version is on the MiStats Mitel Call Accounting website

Posted