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

Encrypt & Decrypt Strings in Silverlight

By , 31 Jul 2012
 

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
Member
I'm from Asuncion, Paraguay I live and work here. I've been a software developer for 10+ years, working with .NET and web standards.
 
During the day I'm a .NET full time developer, working with developers (SCRUM on it!) to help them to bring outstanding WPF, Silverlight and web applications to the Market.
 
In my free time I'm Tien Shan Pai Kung Fu & Kuk Sool Won student. I'm trying to learn mobile development (Android & Windows Phone) and working very hard on it!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberDulce Barrios5 Sep '12 - 16:28 
so good

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 31 Jul 2012
Article Copyright 2012 by Christian Amado
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid