Understanding the New Cryptographic APIs in Window Phone Mango

Introduction

With the launch of Windows Phone Mango,
Microsoft introduced over 500 new features, one of which was a set of new
cryptographic APIs that developers can use in their applications to store
credentials. The credentials can now be stored in an encrypted fashion that reduces
the risk associated with an unencrypted environment like isolated storage.

With the new cryptographic APIs, a user’s confidential data
(e.g. login credentials to a social networking site) can be encrypted instead
of keeping it in plain-text inside isolated storage.

The new Data Protection API (DPAPI) allows applications to
store confidential data like phone PINs, connection strings and passwords in an
encrypted form.

System.Security.Cryptography namespace has a class,
ProtectedData, which provides Protect and Unprotect methods that can be used to
exercise the Data Protection API.

The Protect API is used to encrypt the data and the
Unprotect API is used to decrypt.

The Protect and the Unprotect API have the following
signature,

[SecuritySafeCriticalAttribute]
public static byte[] Protect(
         byte[] userData,
         byte[] optionalEntropy
)
[SecuritySafeCriticalAttribute]
public static byte[] Unprotect(
         byte[] encryptedData,
         byte[] optionalEntropy
)

The entropy parameter can be used to specify increased
complexity of encryption. If entropy is specified for Protect API for some data,
the same value will need to be specified when the Unprotect API is called on the
encrypted data to decrypt it.

Hands-On

Let us create a simple Windows Phone application that uses
these cryptographic APIs.

Create a new Windows Phone application called WPCyrptoDemo.

Create a new Windows Phone application
Figure 1: Create a new Windows Phone application

When prompted for OS version, select 7.1

Select the Windows Phone Platform
Figure 2: Select the Windows Phone Platform

Add a checkbox, a textbox and a Button, as shown in the
picture below.

Add a checkbox, textbox and button
Figure 3: Add a checkbox, textbox and button

The corresponding XAML code is shown below:

<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Login" Height="72" HorizontalAlignment="Left" Margin="121,254,0,0" Name="buttonLogin" VerticalAlignment="Top" Width="160" />
            <CheckBox Content="First Time" Height="72" HorizontalAlignment="Left" Margin="116,174,0,0" Name="checkBoxFirstTime" VerticalAlignment="Top" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="92,129,0,0" Name="textBlock1" Text="PIN" VerticalAlignment="Top" Width="66" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="159,110,0,0" Name="textBoxPIN" Text="" VerticalAlignment="Top" Width="179" MaxLength="4">
            </TextBox>
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="179,69,0,0" Name="textBlock2" Text="Enter PIN" VerticalAlignment="Top" Width="189" />
        </Grid>

On the code-behind file, add a using statement to include
System.IO.IsolatedStorage and System.Security.Cryptography namespace.

// MainPage.xaml.cs
using System.Security.Cryptography;
using System.IO.IsolatedStorage;

Now, add a local variable of type byte[].

public partial class MainPage : PhoneApplicationPage
    {
        byte[] encryptedPINArray;

Implement two helper functions to store and retrieve the pin
from encrypted state.

void StorePin(string text)
        {
            byte[] pinArray = Encoding.UTF8.GetBytes(text);
            encryptedPINArray = ProtectedData.Protect(pinArray, null);
        }
 
        string GetPin()
        {
            byte[] unencryptedPINArray = ProtectedData.Unprotect(encryptedPINArray, null);
            return Encoding.UTF8.GetString(unencryptedPINArray, 0, unencryptedPINArray.Length);
        }

Finally, implement the Click handler for the Login button.
Our login algorithm is as under: When the First Time checkbox is checked, the
PIN will be set. When the checkbox is unchecked, it will decrypt the encrypted
PIN and compare to what we entered. If the comparison succeeds, the status
message will be updated to reflect that the login was successful.

        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxPIN.Text.Length != textBoxPIN.MaxLength)
            {
                textBlockStatus.Text = "Enter a PIN of 4 characters and click Login to continue";
                return;
            }
            if ((bool)checkBoxFirstTime.IsChecked )
            {
                StorePin(textBoxPIN.Text);
                textBoxPIN.Text = "";
                textBlockStatus.Text = "PIN created";
            }
            else
            {
                string storedPin = GetPin();
                if (textBoxPIN.Text == storedPin)
                    textBlockStatus.Text = "Login Successful";
  else
                    textBlockStatus.Text = "Login Unsuccessful";
 
            }
        }

Now, compile and execute the application. When using the
application for the first time, make sure the checkbox “First time” is checked,
so that we can store the PIN for the first time. When we enter the PIN
subsequently, the application will compare the PIN with the stored PIN.

If you are having trouble following along, you can download
a copy of sample code below.

Summary

In this article, we learned about how we can use the new
cryptographic APIs in a Windows Phone Mango application. I hope you have found
this information useful.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read