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

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

  • To encrypt the data with some encryption algorithm
  • Save in the isolated storage

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

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 DP API, all it takes one line of code to encrypt and decrypt the data.

To Encrypt

image

First line of code is converting string to byte array. To encrypt data only you need to pass byte array.

To Decrypt

image

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

If you closely look into ProtectedData class,

image

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

Design page

Now let us design a page like below, 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.

clip_image001

XAML of design is as 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 above code,

  1. We are converting text to 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 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 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 above code,

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

If you would have noticed we have not provided 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 Smile

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.

Triple DES Encryption and Decryption using User provided key

Objective

In this article, I will explain how to do a Triple DES encryption on a plain text using user provided key. I will calculate a MD5 Hash on the key provided by the user. And that key will be user to encrypt and decrypt the message.

Explanation of DES

DES is a symmetric key encryption algorithm. Same key is being used for encryption and decryption. So challenge in using symmetric key algorithm is that we need to have the same key for decryption which is used for encryption. People follow different approach to save key. Either they append key with cryptic text or physically save it somewhere. I am going to ask user to input some string as key. I will calculate MD5 hash on that string input by user to make key. Then I will use this key to encrypt and decrypt the plain text.

Working

  1. User will enter the key
  2. User will enter the plain text
  3. When User will click the Encrypt button, plain text will get encrypted and display in textbox2.
  4. When user will click on Decrypt button in textbox3 plain text will get display.

Screen

Functions

Function to create DES

1 static TripleDES CreateDES(string key)

2 {

3

4 MD5 md5 = newMD5CryptoServiceProvider();

5 TripleDES des = newTripleDESCryptoServiceProvider();

6 des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));

7 des.IV = new byte[des.BlockSize / 8];

8

9 return des;

10 }

This function will create TripleDES instance. This is taking a string as key value and will calculate MD5 hash on input parameter string. This hash value would be used as real key for the encryption.

Function to Encrypt

1

2 publicstaticbyte[] Encryption(string PlainText,string key){

3

4 TripleDES des = CreateDES(key);

5 ICryptoTransform ct = des.CreateEncryptor();

6 byte[] input = Encoding.Unicode.GetBytes(PlainText);

7 return ct.TransformFinalBlock(input, 0, input.Length);

8 }

  1. This function is taking Plain text to encrypt and key
  2. This function is returning a byte array
  3. As parameter for CreateDES , I am passing the key


Function to Decrypt

1 public static string Decryption(string CypherText,string key)

2 {

3 byte[] b = Convert.FromBase64String(CypherText);

4 TripleDES des = CreateDES(key);

5 ICryptoTransform ct = des.CreateDecryptor();

6 byte[] output = ct.TransformFinalBlock(b, 0, b.Length);

7 return Encoding.Unicode.GetString(output);

8 }

  1. This function is taking key and CypherText to encrypt .
  2. It is returning a string.
  3. It is creating TripleDES on given key.


Full Code

The below is the full code for encryption and decryption. There are two button click events on which we are performing the action.


1 using System;

2

3 using System.Collections.Generic;

4

5 using System.ComponentModel;

6

7 using System.Data;

8

9 using System.Drawing;

10

11 using System.Linq;

12

13 using System.Text;

14

15 using System.Windows.Forms;

16

17 using System.Security.Cryptography;

18

19 using System.IO;

20

21 namespace Encryptionusing_Des

22

23 {

24

25

26 public partial class Form1 : Form

27

28 {

29

30

31 public Form1()

32

33 {

34

35 InitializeComponent();

36

37 }

38

39

40 private void Encrypt_Click(object sender, EventArgs e)

41

42 {

43

44

45 byte[] buffer = Encryption(textBox1.Text,txtKey.Text);

46

47

48 string b = Convert.ToBase64String(buffer);

49

50 textBox2.Text = b;

51

52 }

53

54

55 public static byte[] Encryption(string PlainText,string key)

56

57 {

58

59

60 TripleDES des = CreateDES(key);

61

62

63 ICryptoTransform ct = des.CreateEncryptor();

64

65

66 byte[] input = Encoding.Unicode.GetBytes(PlainText);

67

68

69 return ct.TransformFinalBlock(input, 0, input.Length);

70

71 }

72

73

74 public static string Decryption(string CypherText,string key)

75

76 {

77

78

79 byte[] b = Convert.FromBase64String(CypherText);

80

81

82 TripleDES des = CreateDES(key);

83

84

85 ICryptoTransform ct = des.CreateDecryptor();

86

87

88 byte[] output = ct.TransformFinalBlock(b, 0, b.Length);

89

90

91 return Encoding.Unicode.GetString(output);

92

93 }

94

95

96 private void Decrypt_Click(object sender, EventArgs e)

97

98 {

99

100 textBox3.Text = Decryption(textBox2.Text,txtKey.Text);

101

102 }

103

104

105 static TripleDES CreateDES(string key)

106

107 {

108

109

110 MD5 md5 = new

111 MD5CryptoServiceProvider();

112

113

114 TripleDES des = new

115 TripleDESCryptoServiceProvider();

116

117 des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));

118

119 des.IV = new

120 byte[des.BlockSize / 8];

121

122

123 return des;

124

125 }

126

127 }

128

129 }

Output

Conclusion

I discussed how to encrypt and decrypt a text using user provided key. Thanks for reading