robbanp
I'm the co-founder of this website and the tech lead. Follow me on: twitter.com/robertpohl
Blog

The Rob blog

I'm Robert Pohl, the creator and co-founder to ThatsToday. I blog mostly about technology and internet related topics. Follow me on Twitter @robertpohl
Subscribe to RSS

AESAdvanced Encryption Standard (AES) also called the Rijndael cipher, based off a combination of the two Belgian author's names Joan Daemen and Vincent Rijmen.  AES was accepted in 2002 to replace DES cipher and quickly became the preferred encryption choice to hide secret data. AES is a symmetric cipher, also known as shared key cipher, which means that it uses one single key for both encryption and decryption.

In .Net the AES is visible through the System.Security.Cryptography namespace.
I use the RijndaelManaged class in this example to show you how to easily take a object, serialize it to an XML string, encode it to a byte array, and then deserialize it back to a new copy of the original object.

This example originates from a recent project of mine where I needed to securely store a user object containing sensitive information. This way I can quickly load and save my serialized object to disk and have it encrypted using my secret key.

To show you the different steps, I created a Console App that goes through the different steps:


 

 

class Program
    {
        static void Main(string[] args)
        {
            const string SecretKey = "needstobe32bytesneedstobe32bytes"; //need to be 32 bytes for 256 bit encryption

            var oldUser = new User() {Password = "mysecret", Username = "MyName"};
            var str = Serializer.SerializeToString(oldUser); //Serialize User to XML string

            Console.WriteLine("Serialized object: "+str);
            User newUser = Serializer.FromString<User>(str); //Deserialize User from XML string
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: "+oldUser.Username+" and new user name is: "+newUser.Username);
            Console.ReadKey();

            byte[] encryptedOldUser = Security.Encrypt(str, SecretKey); //Encrypt XML string using AES 
            Console.WriteLine("Encrypted old user: "+Encoding.ASCII.GetString(encryptedOldUser));

            Console.WriteLine("****");
            string decryptedOldUser = Security.Decrypt(encryptedOldUser, SecretKey); //Decrypt bytes
            Console.WriteLine("decrypted old user: " + decryptedOldUser);

            User secureUser = Serializer.FromString<User>(decryptedOldUser); //Serialize back to a new User object
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: " + oldUser.Username + " and secure user name is: " + secureUser.Username);
            Console.ReadKey();

        }
    }

It uses two three classes, one User class that is our guinea pig for the experiment, one Serializer helper class, and one Encryption class.

This serializer class is pretty self-explanatory, and has two methods to go from object to XML and back. One note though is the generics in the FromString method, which saves us from doing the casting later on.

public class Serializer
    {
        public static string SerializeToString(object obj)
        {
            XmlSerializer s = new XmlSerializer(obj.GetType());
            TextWriter w = new StringWriter();
            s.Serialize(w, obj);
            return w.ToString();
        }

        public static T FromString<T>(string str)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            var stringReader = new StringReader(str);
            XmlTextReader xmlReader = new XmlTextReader(stringReader);
            return (T)xs.Deserialize(xmlReader);
        }
    }

 

The Security class is an abstraction class to make the encryption and decryption a little smoother. It contains the obvious encrypt/decrypt methods and some underlying methods to help us with our cipher key and initialization vector. Most of the main code here is taken from a Microsoft AES example found here: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx.

I thought it needed a bit more polish to be easier to use with your own key and a static IV, as well as using it along with serialization.

public class Security
    {

        public static byte[] Encrypt(string text, string key)
        {
            return EncryptStringToBytesAes(text, GetKeyFromString(key), GetIV());
        }

        public static string Decrypt(byte[] data, string key)
        {
            return DecryptStringFromBytesAes(data, GetKeyFromString(key), GetIV());
        }

        private static byte[] EncryptStringToBytesAes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }

        private static string DecryptStringFromBytesAes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

        private static byte[] GetIV()
        {
            byte[] iv = { 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8 };
            return iv;
        }
        private static byte[] GetKeyFromString(string key)
        {
            RijndaelManaged myRijndael = new RijndaelManaged();
            ASCIIEncoding encoding = new ASCIIEncoding();
            myRijndael.Key = encoding.GetBytes(key);
            return myRijndael.Key;
        }
    }

 

And finally our little User class:

 

    [Serializable]
    public class User 
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

The next step would be to store the encrypted data to disk or in a database, but I’ll leave that for another blog post! Hope this code can help you to quickly implement serialization and encryption! ☺

I just added a project of mine called Thumbnailer-net to Google Code as an Open Source project. It is written in C# 4.0, VS 2010.

You can find it here: Thumbnailer-net

It is a simple image/thumbnail generation library to scale images from an URL or locally, and you can even create a snapshot of a website!

I use it here on ThatsToday.com.

 

Quick example:

ImageScale scale = new ImageScale(new Uri("http://cnn.com"), 100, 100);
scale.SaveFile(@"c:\cnn_com.png", 100);

These two lines will take a snap shot from CNN.com and generate a 100x100 jpg from it.

 Even after using .Net for years, we tend to write the same utility methods over and over again. Some people put them in external class libraries (my usually is called Parse.MySmartFunction()), but lately I began to move my utilities to into extension methods which was introduced in C# 3.0.

1.    Shorten strings:
Used in almost all my web projects

        public static string Shorten(this string str,int len)
        {
            if (str.Length > len)
            {
                return StripHtml(str.Substring(0, len) + "...");
            }
            return str;
        }

 

2.    Strip HTML from a string:
Very common in different content listings

        public static string StripHtml(this string str)
        {
            return Regex.Replace(str, "</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->", "", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }

 

3.    Convert a string to a MD5Hashed string:
Many API calls require MD5 Hashing

       public static string ToMd5HashString(this string str)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(str);
            data = x.ComputeHash(data);
            string ret = "";
            for (int i = 0; i < data.Length; i++)
                ret += data[i].ToString("x2").ToLower();
            return ret;
        }

 

4.    Convert a XML String to a XmlNode
When you load XML from the database

     public static  XmlNode ToXmlNode(this string str)
        {
            NameTable nt = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
            nsmgr.AddNamespace("", "");
            XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

            XmlTextReader reader = new XmlTextReader(str, XmlNodeType.Element, context);
            XmlDocument doc = new XmlDocument();
            XmlNode node = doc.ReadNode(reader);
            return node;
        }

 

 

5.    Bytes to Megabytes:
Easy but tiresome number conversions.

        public static double BytesToMegabytes(this long bytes)
        {
            return (bytes / 1024f) / 1024f;
        }

 

 

My friends at Raketspel have released yet another stunning web game, and this time it's all about football! You can pick any countries and create a tournament. It's easy to play and extremely fun!

Try out Simple Soccer Championship here !

 

WebMffmpeg

 

FFMPEG is the universal Go-To app for everyone that want to work with video on the web. It has been used for basically every YouTube clone out there and is both easy to use, fast and totally free.

The biggest problem with FFMPEG has been the missing support for the Flash Video Codec VP8 that offers the best quality for Flash Video.

The good news is that since Google bought On2 Technologies that is behind the VP8 codec, they have now published it freely using BSD license.

The WebM Project aim to spread a high quality, open video format for the web that is freely available to avaryone, and it is supported by Mozilla, Opera, Google and others. And yeah, Internet Explorer 9 will also support VP8, so it looks like we have a winner in the HTML5 video codec battle?

WebM includes:

  • VP8, a high-quality video codec we are releasing today under a BSD-style, royalty-free license
  • Vorbis, an already open source and broadly implemented audio codec
  • a container format based on a subset of the Matroska media container

 

FFmpeg Patches

They provide patches against FFmpeg revision #23190 (trunk, on May 19, 2010), which add VP8 and WebM support. Get them at our downloads page.

There are instructions at FFmpeg.org for acquiring the FFmpeg source code. Using Subversion, you would checkout the source with the following command:

$ svn checkout -r 23190 svn://svn.ffmpeg.org/ffmpeg/ ffmpeg

A git repository is also available at FFmpeg.org.

DirectShow Filters

We provide DirectShow filters for playing and working with WebM on Windows. Once the filters are installed on your system, applications that use the DirectShow framework (such as Windows Media Player, and others) will be able to play and encode WebM media. Note that you’ll also need to install Vorbis audio support.

Follow these steps to get started with VP8 and FFMPEG:

  1. Visit the downloads page.

  2. Download the latest .zip archive of filters. The download filename is similar to

    webmdshow-<version number>-<date>.zip
  3. The archive contains Windows .dll files. These are the DirectShow filters. Extract them to your disk.

  4. In a command shell, change (cd) to the directory (folder) where you extracted the filters.

  5. Register the filters on your system with the following command:

    c:\webmdshow-0.9.4.0\>regsvr32 webmsource.dll webmsplit.dll vp8decoder.dll vp8encoder.dll webmmux.dll
  6. To later uninstall the WebM DirectShow filters, use the following command:

    c:\>regsvr32 /u webmsource.dll webmsplit.dll vp8decoder.dll vp8encoder.dll webmmux.dll
  7. WebM files contain Vorbis audio, but Windows does not currently support Vorbis by default. An easy way to remedy this is to install the set of DirectShow filters provided by the Xiph Foundation. Download at Xiph.org

 

UPDATE

Michael Adams have made an really easy example how to install this in Windows:
http://unquietwiki.blogspot.com/2010/05/install-webm-vp8-on-your-windows-box.html

 

funny

 

This is an awesome team with an awesome business idea that came to life today!

I think we are on to something great here! I'll keep you posted later on ;)

.NET
Performance Testing and Optimization eBookIn the complete guide to .NET Performance Testing and Optimization, Paul Glavich and Chris Farrell offer a comprehensive handbook to anybody looking to set up a .NET testing environment and get the best results out of it. The authors will also walk you through both memory and performance profiling and suggest steps you can take toget fast performance gains

 

 

 

 

 

  • Chapter 01: Introduction - The What and the Why
  • Chapter 02: Understanding Performance Targets
  • Chapter 03: Performance and Load Test Metrics
  • Chapter 04: Implementing your Test Rig
  • Chapter 05: Creating Performance Tests
  • Chapter 06: Next Steps - Profiling
  • Chapter 07: Performance Profiling
  • Chapter 08: Memory Profiling
  • Chapter 09: The Performance Testing Process
  • Chapter 10: Common Areas for Performance Improvement
  • Chapter 11: Load Balancing
  • Chapter 12: Internet Information Server (IIS)
  • Chapter 13: HTTP Optimization

 

Download free eBook


 

 

 

 

 

Original post: http://www.red-gate.com/products/ants_performance_profiler/want_to_be_dotnet_perf_testing_expert_ebook.htm

Slides on AJAX Performance Anti-Patterns by Andreas Grabner.

This is a great presentation with a lot of do's and dont's when it comes to AJAX and JavaScript DOM programming.

Sign In

Not a member yet?

Signing up is FREE and will only take 15 seconds!

Facebook Login

Sign In

E-mail address:
Password:
Remember me
Sponsored links
AdUniver.se - ad platform Create wish-list e-böcker ljudböcker till din ipad android läsplatta dator

Close