Encrypt your AJAX traffic using Microsoft Silverlight and Ajax.NET Professional

Michael Schwarz on Thursday, November 13, 2008

Some of you maybe remember that I had added some security related features in Ajax.NET Professional [1]. It is possible to put an AJAX token or to simple encrypt the data that gets over the lines. With Silverlight [2] we get the System.Security.Cryptography namespace on the client – before it was not very easy to encrypt a string without any plug-in (well, there are some implementations of Blowfish available in JavaScript [3]).

I have created a very simple demo that is showing how to implement cryptography in Ajax.NET Professional.

First we have to create the encryption methods and implement an AjaxSecurityProvider:

public override string Encrypt(string json)
{
  return Security.Encrypt(Security.GetHashKey("hans"), json);
}

public override string Decrypt(string jsoncrypt)
{
  return Security.Decrypt(Security.GetHashKey("hans"), jsoncrypt);
}

With Silverlight you’re able to use the html bridge between JavaScript and managed .NET code. You’ll find an example in the Silverlight Quickstarts [4]. The Silverlight C# code looks likes this:

public class ScriptableManagedType
{
  // Note: static methods are not allowed

  [ScriptableMember]
  public string Encrypt(string text)
  {
    return Security.Encrypt(Security.GetHashKey("hans"), text);
  }

  [ScriptableMember]
  public string Decrypt(string text)
  {
    return Security.Decrypt(Security.GetHashKey("hans"), text);
  }
}

With the html bridge and some client-side code you’re able to encrypt strings in JavaScript with the help of System.Security. In the AjaxSecurityProvider created above you have to override the ClientScript property to let Ajax.NET Professional encrypt the JSON strings using Silverlight:

public override string ClientScript
{
  get
  {
    return @"AjaxPro.cryptProvider = {
      encrypt : function(s) {
        var SLPlugin = document.getElementById(""Xaml1"");
        var strOut = SLPlugin.Content.SL_SMT.Encrypt(s);
        return strOut;
      },
      decrypt : function(s) {
        var SLPlugin = document.getElementById(""Xaml1"");
        var strOut = SLPlugin.Content.SL_SMT.Decrypt(s);
        return strOut;
      }
    };";
  }
}

Hey, that’s everything you have to do to add encryption to your Ajax.NET Professional enabled Web sites. There is no source code change needed in your files except of including the Silverlight control.

Look at the screenshot from Fiddler [5] using this example [6]:

image

In my example I’m using "hans" as password which, of course, is not the way it should be implemented later (have in mind that it is very easy to analyze the Silverlight files and use .NET Reflector [7] to get the password there). What could be used is the IsolatedStorage to enter once the password that you get i.e. by mail when you register first time on the Web site.

Download the example project here [6].