Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Encrypt & Decrypt Strings in Silverlight

0.00/5 (No votes)
31 Jul 2012 1  
A very brief article about the implementation of encryption and decryption of a string in Silverlight Business Application

Introduction

Sometimes is very helpful to Encrypt and Decrypt strings in our applications, especially when we transmit sensible data over the net or between applications inside our own machines.

In Silverlight applications we can Encrypt & Decrypt strings easily following some steps and writing some lines of code on a extension class.

Background

This article take care about two things that we going to discuss here:

1. Encrypt & Decrypt strings inside Silverlight Application (out-of-the-browser).

2. Encrypt & Decryt string inside Silverligth Business Application (communication between Service & Silverlight Application)

The main idea here is to demonstrate How to encrypt & Decrypt the same value in server & client application, because the communication between them are in plain text.

Using the Code

Encrypt and Decrypt string inside Silverlight Application

Well, here we must create a simple Silverlight Business Application in our Visual Studio. In my case I called my project Encrypt_Decrypt_SBA.

Now we going to create a extension method for all strings in our Silverlight project, the class will be static and exposes two main methods: Encrypt() and Decrypt() just read the code below:

namespace Encrypt_Decrypt_SBA.Helpers
{
    /// <summary>
    /// A simple class available only in this Assembly
    /// </summary>
    internal static class Cryptography
    {
        internal static string Encrypt(this string dataToEncrypt)
        {
            // Initialize
            AesManaged encryptor = new AesManaged();
            
            // Get the string salt, on this case I pass a hard coded value. Then, create the byte[]
            string salt = "EDSBA_EXAMPLE";
            byte[] saltBytes = new UTF8Encoding().GetBytes(salt);
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(salt, saltBytes);

            encryptor.Key = rfc.GetBytes(16);
            encryptor.IV = rfc.GetBytes(16);
            encryptor.BlockSize = 128;

            // create a memory stream
            using (MemoryStream encryptionStream = new MemoryStream())
            {
                // Create the crypto stream
                using (CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    // Encrypt
                    byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
                    encrypt.Write(utfD1, 0, utfD1.Length);
                    encrypt.FlushFinalBlock();
                    encrypt.Close();

                    // Return the encrypted data
                    return Convert.ToBase64String(encryptionStream.ToArray());
                }
            }
        }

        internal static string Decrypt(this string encryptedString)
        {
            // Initialize
            AesManaged decryptor = new AesManaged();
            byte[] encryptedData = Convert.FromBase64String(encryptedString);

            // Get the string salt, on this case I pass a hard coded value. Then, create the byte[]
            string salt = "EDSBA_EXAMPLE";
            byte[] saltBytes = new UTF8Encoding().GetBytes(salt);
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(salt, saltBytes);

            decryptor.Key = rfc.GetBytes(16);
            decryptor.IV = rfc.GetBytes(16);
            decryptor.BlockSize = 128;

            // create a memory stream
            using (MemoryStream decryptionStream = new MemoryStream())
            {
                // Create the crypto stream
                using (CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    try
                    {
                        // Encrypt
                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                        decrypt.Close();
                    }
                    catch { }

                    // Return the unencrypted data
                    byte[] decryptedData = decryptionStream.ToArray();
                    return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
                }
            }
        }
    }
}

In the code above, we created two method extensions for all strings inside the Silverlight project, in this way we can implement easily the encryptation to any string inside the project.

Run the project (F5) and test it! 

Encrypt & Decrypt strings in Silverlight Business Application

In this case we need to create a class to implement the same algorithm that we used on our Silverlight Application.

So we can create the same class and exposes the same set of methods inside it, so the code will be:

namespace Encrypt_Decrypt_SBA.Web
{
    /// <summary>
    /// A simple class available only in this Assembly
    /// </summary>
    internal static class Cryptography
    {
        internal static string Encrypt(this string dataToEncrypt)
        {
            // Initialize
            AesManaged encryptor = new AesManaged();

            // Get the string salt, on this case I pass a hard coded value. Then, create the byte[]
            string salt = "EDSBA_EXAMPLE";
            byte[] saltBytes = new UTF8Encoding().GetBytes(salt);
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(salt, saltBytes);

            encryptor.Key = rfc.GetBytes(16);
            encryptor.IV = rfc.GetBytes(16);
            encryptor.BlockSize = 128;

            // create a memory stream
            using (MemoryStream encryptionStream = new MemoryStream())
            {
                // Create the crypto stream
                using (CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    // Encrypt
                    byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
                    encrypt.Write(utfD1, 0, utfD1.Length);
                    encrypt.FlushFinalBlock();
                    encrypt.Close();

                    // Return the encrypted data
                    return Convert.ToBase64String(encryptionStream.ToArray());
                }
            }
        }

        internal static string Decrypt(this string encryptedString)
        {
            // Initialize
            AesManaged decryptor = new AesManaged();
            byte[] encryptedData = Convert.FromBase64String(encryptedString);

            // Get the string salt, on this case I pass a hard coded value. Then, create the byte[]
            string salt = "EDSBA_EXAMPLE";
            byte[] saltBytes = new UTF8Encoding().GetBytes(salt);
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(salt, saltBytes);

            decryptor.Key = rfc.GetBytes(16);
            decryptor.IV = rfc.GetBytes(16);
            decryptor.BlockSize = 128;

            // create a memory stream
            using (MemoryStream decryptionStream = new MemoryStream())
            {
                // Create the crypto stream
                using (CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    try
                    {
                        // Encrypt
                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                        decrypt.Close();
                    }
                    catch { }

                    // Return the unencrypted data
                    byte[] decryptedData = decryptionStream.ToArray();
                    return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
                }
            }
        }
    }
}

Now we going to create a WCF Service for Silverlight, inside the Services folder. Name it ServiceTest.svc and create the following two methods on it:

namespace Encrypt_Decrypt_SBA.Web.Services
{
    [ServiceContract(Namespace = "")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ServiceTest
    {
        [OperationContract]
        public void DoWork()
        {
            return;
        }

        [OperationContract]
        public string EncryptString(string unencrypted)
        {
            return unencrypted.Encrypt();
        }

        [OperationContract]
        public string DecryptString(string encrypted)
        {
            return encrypted.Decrypt();
        }
    }
}

Build your Web project. And Add the Service reference on Silverlight Application project. 

Now, just call the encrypted string on the server and just compare to the Silverlight Application TextBox, just like this: 

private void btnEncryptService_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //Instanciate the proxy for ServiceTest
            ServiceTest.ServiceTestClient proxy = new ServiceTest.ServiceTestClient();
            //Call to the completed event of that proxy
            proxy.EncryptStringCompleted += (s, args) =>
            {
                this.simpleTextService.Text = string.Empty;
                this.EncryptedTextService.Text = args.Result;
            };
            //Call the async method and pass the parameter
            proxy.EncryptStringAsync(this.simpleTextService.Text);
        }

        private void btnDencryptService_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //Instanciate the proxy for ServiceTest
            ServiceTest.ServiceTestClient proxy = new ServiceTest.ServiceTestClient();
            //Call to the completed event of that proxy
            proxy.DecryptStringCompleted += (s, args) =>
            {
                MessageBox.Show("Via service: "+args.Result);
                this.EncryptedTextService.Text = string.Empty;
            };
            //Call the async method and pass the parameter
            proxy.DecryptStringAsync(this.EncryptedTextService.Text);
        } 

Copyright

The cryptography algorithm it's not mine. I downloaded from here a year ago. So, the algorithm exists thanks to chrishayuk

Points of Interest 

This article exposes How you can implement encryption and decryption of any string in Silverlight application and also between the server.

It's very important in some case. I know that you can create so many ways to implement this escenario. This is just only one way to do that.

What's next?

Just download the source code and play with it! 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here