16 October, 2011

WP7: Protecting connection strings and passwords

When you are dealing with sensitive data, such as passwords etc. in a Windows Phone 7 application, you can make use of the DPAPI (Data Protection API). This is roughly the same as the one found on the Windows Operating System.

The neat thing about the wrapping found in Silverlight for WP7 is, that Encryption and Decryption has been wrapped so nicely that they have become very easy to use. In the below – I’m encrypting a simple textbox value just for the proof-of-concept. Next – the value is retrieved from disk and decrypted for plain text view.

image

Note: the DPAPI of WIndows Phone uses the logged in UserID as well as the applicationID to generate the secret keys that allows the DPAPI to revert the encrypted bytes when you need them again.

The 2 buttons seen above invokes this code:

Encrypt:

/// <summary>
///
save encrypted data -> "datafile" (in isolated storage)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Encrypt_Click(object sender, RoutedEventArgs e)
{
//convert to bytes
byte[] plainData = Encoding.UTF8.GetBytes(textBox1.Text);
byte[] encryptedData = ProtectedData.Protect(plainData, null);

IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = file.OpenFile("datafile.dat", System.IO.FileMode.OpenOrCreate))
{
//write files into file
var bw = new BinaryWriter(fs);
bw.Write(encryptedData);
bw.Flush();
}
}

Decrypt;

/// <summary>
///
load file and decrypt
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Decrypt_Click(object sender, RoutedEventArgs e)
{
using (var fs = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("datafile.dat", FileMode.Open))
{
var br = new BinaryReader(fs);
byte[] encryptedData = br.ReadBytes((int)fs.Length);

byte[] plainData = ProtectedData.Unprotect(encryptedData, null);
textBox1.Text = Encoding.UTF8.GetString(plainData, 0, plainData.Length);
}

}


How easy can it get?


StackOverflow Tags:

No comments:

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...