Protecting user's confidential information is so important and it becomes even more when developing apps for mobile devices.
When you create applications for Windows Phone you can still use existing skills related to the System.Security.Cryptography namespace of the .NET Framework, and one existing technique offers a simplified way to protect information via encryption.
There is a class called ProtectedData which exposes two shared methods, Protect and Unprotect. The first method receives a string and returns its content under the form of an encrypted array of byte. The second method receives the encrypted array and returns the original, unprotected string.
That said, let's see how to define a class that implements this technique:
Imports System.Security.Cryptography
Imports System.Text
Public Class CryptoService
Public Shared Function EncryptString(data As String) As Byte()
Dim PinByte = Encoding.UTF8.GetBytes(data)
Dim ProtectedPinByte = ProtectedData.Protect(PinByte, Nothing)
Return ProtectedPinByte
End Function
Public Shared Function DecryptData(data As Byte()) As String
Dim unprotected = ProtectedData.Unprotect(data, Nothing)
Return Encoding.UTF8.GetString(unprotected, 0, unprotected.Length)
End Function
End Class
The first method called EncryptString first converts the string into an array of byte and then encrypts the latter via the ProtectedData.Protect method. As opposite, the second method called DecryptData first unprotects the information into an array of byte which is finally converted into the original string. Using this technique is strictly related to the isolated storage. The following code demonstrates how to encrypt and save a string:
Dim store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication
Using protStream As New IsolatedStorageFileStream("myfile.bin", IO.FileMode.Create, store)
Dim data = "Confidential string, do not share"
Dim protectedData = CryptoService.EncryptString(data)
protStream.Write(protectedData, 0, protectedData.Length)
End Using
The following code demonstrates how to retrieve the previously encrypted string from a stream:
Using protStream As New IsolatedStorageFileStream("myfile.bin", IO.FileMode.Open, store)
Dim pinArray As Byte() = New Byte(CInt(protStream.Length - 1)) {}
protStream.Read(pinArray, 0, pinArray.Length)
Dim info = CryptoService.DecryptData(pinArray)
End Using
You might want to consider using different techniques for additional protection, however this is very simple and efficient. Don't miss the official MSDN documentation about it.
Alessandro