Understanding the New Cryptographic APIs in Window Phone Mango


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,

public static byte[] Protect(
         byte[] userData,
         byte[] optionalEntropy
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.


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">
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="179,69,0,0" Name="textBlock2" Text="Enter PIN" VerticalAlignment="Top" Width="189" />

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";
            if ((bool)checkBoxFirstTime.IsChecked )
                textBoxPIN.Text = "";
                textBlockStatus.Text = "PIN created";
                string storedPin = GetPin();
                if (textBoxPIN.Text == storedPin)
                    textBlockStatus.Text = "Login Successful";
                    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.


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.

About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Related Articles



  • Cheap Oakley Monster Dog wholesale online

    Posted by ablulxasz on 06/24/2013 11:55am

    Cheap ray ban sunglasses ,The sunglasses generally known as sun mirror (or sunglasses) generally must prevent glare, UV and glare. Can not be denied the reality is that the market equipment and items for ladies is far higher than men's accessories market Japanese products. fake oakley sunglasses ,Oakley sunglasses are always leading in the field of science and technology, the use of high-tech, in order that they time and again beyond the limit, test in numerous projects, to check all possible to assume circumstances Ongoing research and progress, Oakley sunglasses have grown up to become redundant and further productivity than for many years, focused on quality, excellence, fabricated sunglasses, including the hinge of each and every single component. Discount Oakley Holbrook ,Bring modifications in fashion and traditional concepts. You wish to have your unique fashion style. Brook Oakley sunglasses are your better choice! Top quality and technology experts, each design is clear that is a perfect brand, if you like a smart and effortlessly cool finish for your look. The sunglasses, using time, determined by your usage habits, however, lots of friends wearing sunglasses too casual as well as doesn't attach importance for the upkeep of the sunglasses. At the sea or sailing: you'll discover a broad building or housing to dam the sun or sky, not many individuals are up against a one, and from the reflection of diffuse radiation as well as the water inside entire sky. Oakley shades of further vision defensive purposes, as the contacts are packed all around your temples or the WATS maintain many more?? Gentle. If you will be outside walking for the glasses, accomplish this, to enable you to understand how they will truly have permission to function under the sun. High technology and perfect design of the Oakley, the legendary faraway from fashion or can be described as a genius. The best-selling sunglasses, particularly for ladies fashion sunglasses, you are able to develop a tremendous impact has its own personality. Clothing, including different materials, that's pleasant and cozy complexion. Also, women's clothing are located in different colors, patterns and standards of measurement. Do you have a wonderful pair after some research and dedication part, you must simply select the appropriate form of Oakley sunglasses in order to meet every single need.

  • monster beats hovedtelefoner fremragende kvalitet, der oversteg

    Posted by wanzixiao on 06/04/2013 04:19am

    [url=http://www.beatsbydrdredanmark.350.com/]beats by dre danmark[/url] Samarbejdet om lettelse af Beats by Dre viser sig at være en ganske indbringende forretning for dette selskab, som der er store statistik over salg og tilbagemeldinger er god som derved øger den samlede tilbagemelding af selskabet. Vkhifi.com sikrer, at de produkter, der leveres ordentligt til slutbrugere, og at der ikke er nogen klager. Hvis der er, er draget omsorg for at løse problemet med kunder, der har købt produktet. Selvom de andre sammen med Hovedtelefoner beats aldrig har stået over for en sådan problem og kundernes feedback er generelt god, disse er politikker, der fastsættes af selskabet. Om Vkhifi.com Selskabet Vkhifi.com er én stor vove sig ind i lettelse af beats, der rocke digitale verden. Hovedtelefoner og headsets, som nogle af de allerbedste spillere på det globale marked som DRE, Monster og headsets indikerer, at selskabet har til formål at sætte en høj klasse af forretningssted i et betydeligt kort tidsrum. Virksomheden Formanden erklærede en vandretur i erhvervslivet lønsomhed med indførelsen af disse nye produkter og forventes at nå ganske høj med fremskridt inden for teknologi. [url=http://www.nyebeatsbydrdre.350.com/]Nye beats by dr dre[/url] Based hovedtelefoner tilbyde lydkvalitet, der er lige så forbløffende. Ideel til nutidens digitale musik, disse hovedtelefoner giver dyb bas, en fed mellemtone, og klar, uforvrænget diskant, så du kan høre hver detail.The on-ear, lukket-back design giver langvarig komfort og en høj grad af naturlig støj isolation . Den enkeltsidede kabel er designet til at give dig masser af slæk mens modstå tangles. Integreret i kablet er Monsters ControlTalk modul, som giver dig en kontrolknap og high-grade mikrofon, ideel til styring musikafspilning, telefonopkald og tage stemmenotater på kompatible iPods, iPhones, og Blackberrys. Den guldbelagt 3,5 mm stik giver bred kompatibilitet med MP3-afspillere, cd-afspillere, computere og meget mere. [url=http://www.beatsbydrdredanmark.webgarden.com/]beats by dre tilbud[/url] Uanset om du har brug for netværks personlig brug derhjemme, eller hvis du har brug for at udstyre dit barns skole, som er en meget sød, med henblik på at få en favorit Beats hovedtelefoner nysgerrig, jeg gravede lidt dybere, og jeg gotta jeg ser frem til i alle de basale behov klik her. Faktisk ønsker jeg dig til at bryde det ned til den korte form.Da jeg fik den elskede monster beats hovedtelefoner, og jeg føler meget glad og spændt, men hvad er den virkelige god pleje af det, selv om de nye hovedtelefoner altid vil indtage markedet hurtigt, men når jeg har beats er stadig som ny, tilfredshed aldrig forladt. Vi taler om nogle enkle opførsel om forlængelse af levetiden for headsettet

  • louis vuitton purses replica

    Posted by GypeNoge on 10/30/2012 03:50pm

    get knockoff louis vuitton handbags , just clicks away aPNdKcuc http://www.replicalouis-vuitton.org/

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date