Click here to Skip to main content
15,868,141 members
Articles / Security / Cryptography
Tip/Trick

Encrypt & Decrypt Strings in Silverlight

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
31 Jul 2012CPOL2 min read 25.1K   803   5   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:

C#
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:

C#
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:

C#
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: 

C#
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)


Written By
Architect
Paraguay Paraguay
hristian Amado is a professional software engineer, professional developer and trainer with over 18 years of experience building applications for Windows Desktop and the Web. Located in Asuncion, Paraguay, He's well involved in many Microsoft's technologies including XAML, C#, X++, WCF, ADO.NET and ASP.NET.

He holds a several Microsoft certifications including Microsoft Certified Professional Developer (MCPD), Microsoft Certified IT Professional, Microsoft Certified Technology Specialist and Microsoft Office Specialist.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Dulce Barrios5-Sep-12 16:28
Dulce Barrios5-Sep-12 16:28 
so good

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

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