Click here to Skip to main content
Click here to Skip to main content

Encrypt & Decrypt Strings in Silverlight

, 31 Jul 2012
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Christian Amado
Software Developer
Paraguay Paraguay
Christian Amado is a professional software engineer, pro developer and trainer with over 12 years of experience building application for Windows Desktop and the Web. Located in Asuncion, Paraguay, He is well involved in many Microsoft's technologies including XAML, C#, WCF, ADO.NET and ASP.NET.
 
Christian is quick to embrace new development technologies and has won some awards in programming competitions organized by communities. He has been the only paraguayan who participated in the beta program of Windows Phone 8, and is a member of the Microsoft User Group Paraguay. He is also involved in the Microsoft Student Partner program helping nominees students and is the Group Leader in the only Windows Phone Developers Group in Paraguay.
 
He holds a several Microsoft certifications including Microsoft Certified Professional Developer (MCPD), Microsoft Certified IT Professional, Microsoft Certified Technology Specialist and Microsoft Office Specialist.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberDulce Barrios5-Sep-12 16:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 31 Jul 2012
Article Copyright 2012 by Christian Amado
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid