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
{
internal static class Cryptography
{
internal static string Encrypt(this string dataToEncrypt)
{
AesManaged encryptor = new AesManaged();
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;
using (MemoryStream encryptionStream = new MemoryStream())
{
using (CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
return Convert.ToBase64String(encryptionStream.ToArray());
}
}
}
internal static string Decrypt(this string encryptedString)
{
AesManaged decryptor = new AesManaged();
byte[] encryptedData = Convert.FromBase64String(encryptedString);
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;
using (MemoryStream decryptionStream = new MemoryStream())
{
using (CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
try
{
decrypt.Write(encryptedData, 0, encryptedData.Length);
decrypt.Flush();
decrypt.Close();
}
catch { }
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
{
internal static class Cryptography
{
internal static string Encrypt(this string dataToEncrypt)
{
AesManaged encryptor = new AesManaged();
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;
using (MemoryStream encryptionStream = new MemoryStream())
{
using (CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
return Convert.ToBase64String(encryptionStream.ToArray());
}
}
}
internal static string Decrypt(this string encryptedString)
{
AesManaged decryptor = new AesManaged();
byte[] encryptedData = Convert.FromBase64String(encryptedString);
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;
using (MemoryStream decryptionStream = new MemoryStream())
{
using (CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
try
{
decrypt.Write(encryptedData, 0, encryptedData.Length);
decrypt.Flush();
decrypt.Close();
}
catch { }
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)
{
ServiceTest.ServiceTestClient proxy = new ServiceTest.ServiceTestClient();
proxy.EncryptStringCompleted += (s, args) =>
{
this.simpleTextService.Text = string.Empty;
this.EncryptedTextService.Text = args.Result;
};
proxy.EncryptStringAsync(this.simpleTextService.Text);
}
private void btnDencryptService_Click(object sender, System.Windows.RoutedEventArgs e)
{
ServiceTest.ServiceTestClient proxy = new ServiceTest.ServiceTestClient();
proxy.DecryptStringCompleted += (s, args) =>
{
MessageBox.Show("Via service: "+args.Result);
this.EncryptedTextService.Text = string.Empty;
};
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!