Pages

Wednesday, July 27, 2011

Encryption in Silverlight and .NET Applications

I wanted to encrypt some sensitive data in a Silverlight application and decry pt that in the server. Sergey Barskiy's has written a good post about that. Here is the code.

Encryption functionality

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Encryption
{
public static class EncryptionUtility
{

///
/// Encrypt the data
///

/// String to encrypt
/// Encrypted string
public static string Encrypt(string input, string password)
{

byte[] utfData = UTF8Encoding.UTF8.GetBytes(input);
byte[] saltBytes = Encoding.UTF8.GetBytes(password);
string encryptedString = string.Empty;
using (AesManaged aes = new AesManaged())
{
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);

aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);

using (ICryptoTransform encryptTransform = aes.CreateEncryptor())
{
using (MemoryStream encryptedStream = new MemoryStream())
{
using (CryptoStream encryptor =
new CryptoStream(encryptedStream, encryptTransform,CryptoStreamMode.Write))
{
encryptor.Write(utfData, 0, utfData.Length);
encryptor.Flush();
encryptor.Close();

byte[] encryptBytes = encryptedStream.ToArray();
encryptedString = Convert.ToBase64String(encryptBytes);
}
}
}
}
return encryptedString;
}

Decryption functionality

///
/// Decrypt a string
///

/// Input string in base 64 format
/// Decrypted string
public static string Decrypt(string input, string password)
{


input = input.Replace(" ","+");
byte[] encryptedBytes = Convert.FromBase64String(input);
byte[] saltBytes = Encoding.UTF8.GetBytes(password);
string decryptedString = string.Empty;
using (var aes = new AesManaged())
{
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);

using (ICryptoTransform decryptTransform = aes.CreateDecryptor())
{
using (MemoryStream decryptedStream = new MemoryStream())
{
CryptoStream decryptor =
new CryptoStream(decryptedStream, decryptTransform,CryptoStreamMode.Write);
decryptor.Write(encryptedBytes, 0, encryptedBytes.Length);
decryptor.Flush();
decryptor.Close();

byte[] decryptBytes = decryptedStream.ToArray();
decryptedString =
UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
}
}
}

return decryptedString;
}
}
}
In the decrpting part I had to include the line input = input.Replace(" ","+");
It seems 64-bic encoding does not work with spaces. Plus sign will be interpreted as a space when you call the FromBase64String method.





No comments: