Protecting passwords or any data in Windows Phone 7 using the Data Protection API


There may be many scenarios, when you need to save data in a protected form for your application in isolated storage. Of course you have an option

  1. To encrypt the data with some encryption algorithm
  2. Save in the isolated storage

Problem with the above approach is either you will have to store the key in isolated storage or read it from some external sources. In major scenarios, the key resides on the phone itself and it brings in the flaw.

The Windows Phone Data Protection API helps us to protect data at the application level. On Windows Phone 7, every application has their own key.

This key gets created when you first run the application.

Using the DP API, all it takes is one line of code to encrypt and decrypt the data.

To Encrypt

PrtcAPI1.gif

The first line of code is converting a string to a byte array. To encrypt data, you only need to pass a byte array.

To Decrypt

PrtcAPI2.gif

Password is the name of the file in which the encrypted data is stored. All it takes is only one line of code to decrypt.

If you look closely into the ProtectedData class,

PrtcAPI3.gif

This is a static class with two static methods. If required, you can pass entropy as a parameter also.

Design page

Now let us design a page like below, The design is very simple with one text box taking input to protect the data. There are two buttons, one to protect data and another to decrypt and retrieve protected data.

PrtcAPI4.gif

XAML of the design is below,

<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">           
           
<TextBlock x:Name="PageTitle" Text="protected data" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
        </StackPanel>     
       
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="80" />
                <RowDefinition Height="180" />              
           
</Grid.RowDefinitions>
            <TextBox x:Name="txtDataToProtect" HorizontalAlignment="Left" Width="450" Height="80" />
            <StackPanel Orientation="Horizontal" Margin="0,0,0,0" Grid.Row="1">
            <Button x:Name="btnReteriveData" Content="Reterive" Height="100"  Click="btnReteriveData_Click" Width="200" />
            <Button x:Name="btnProtectData" Content="Protect" Height="100"  Click="btnProtectData_Click" Width="260" />
            </StackPanel>
        </Grid>
    </Grid>

Protecting Data

private void btnProtectData_Click(object sender, RoutedEventArgs e)
        {
            byte[] passwordData = Encoding.UTF8.GetBytes(txtDataToProtect.Text);
            byte[] EncryptedPasswordData = ProtectedData.Protect(passwordData, null);
            SaveToFile(EncryptedPasswordData, "password");
        }


In the above code,

  1. We are converting text to a byte array
  2. Passing byte array to protect
  3. We are applying no entropy.
  4. Saving protected data to a file called password. We will have to fetch encrypted data from file password while retrieving.
  5. To save protected data calling a function called SaveToFile

SaveToFile function

private void SaveToFile(byte[] EncryptedPasswordData,string FileName)
        {
            IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Create, FileAccess.Write, getApplicationFile);
            Stream writer = new StreamWriter(fileAsStream).BaseStream;
            writer.Write(EncryptedPasswordData, 0, EncryptedPasswordData.Length);
            writer.Close();
            fileAsStream.Close();           
        }


In the above code,

  1. We are passing byte array to save
  2. We are passing filename to say where to save the data in application
  3. Reading application file and opening it as file stream
  4. Writing byte array to file stream.

Decrypting data

private void btnReteriveData_Click(object sender, RoutedEventArgs e)
        {
            byte[] data = ReadFromFIle("password");
            byte[] passwordByte = ProtectedData.Unprotect(data, null);
            string password = Encoding.UTF8.GetString(passwordByte, 0, passwordByte.Length);
            txtDataToProtect.Text = password;          
           
        }

In the above code,

  1. We are first reading encrypted data from the isolated storage file. If you notice file name is same.
  2. Calling unprotect method and passing encrypted byte array to decrypt.
  3. Converting decrypted byte array to string and displaying in text box

ReadFromFile function

private byte[] ReadFromFIle(string FileName)
        {
           
            IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Open, FileAccess.Read, getApplicationFile);
            Stream reader = new StreamReader(fileAsStream).BaseStream;
            byte[] password = new byte[reader.Length];
            reader.Read(password, 0, password.Length);
            reader.Close();
            fileAsStream.Close();
            return password;
        }


In the above code,

  1. Reading application file and opening it as file stream
  2. Reading byte array to file stream.

If you have noticed. we have not provided a  KEY either to ENCRYPT or DECRYPT the data.

In this way you can protect data in Windows Phone 7. I hope this post was useful. Thanks for reading.

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Up Next
    Ebook Download
    View all
    Learn
    View all