Namespaces
Variants
Actions

Encrpting and Decrypting data using RSA in Windows Phone

Jump to: navigation, search

This article explains how to encrypt and decrypt data using RSA algorithm in Windows Phone.

Note.png
Note: This is a community entry in the Windows Phone 8 Wiki Competition 2012Q4.
SignpostIcon Code 52.png
MultiMediaTile.png
Article Metadata

Tested with
Devices(s): Windows Phone 8.0 emulator.

Compatibility
Platform(s): Windows Phone

Article
Created: mehul_raje (08 Nov 2012)
Last edited: hamishwillee (22 Apr 2013)

Introduction

This article explains how to use RSA algorithm to encrypt and decrypt data.

How to Encrypt

  • First create new Windows Phone project in VS 2012
  • Add namespace System.Security.Cryptography in the code behind file, which in my case is the default MainPage.xaml.cs

In this example, I used RSACryptoServiceProvider class which inherits from RSA class and performs asymmetric encryption and decryption using the RSA algorithm.

Declare the data members:

  1. rsaProvider of type RSACryptoServiceProvider
  2. byteConverter of type UnicodeEncoding.

Note that rsaProvider helps in encryption and decryption whereas byteConverter helps in conversion of string to byte array and vice versa.

The following function explains how to encrypt the data:

private Byte[] Encrypt(string dataToEncrypt)
{
Byte[] data = this.byteConverter.GetBytes(dataToEncrypt);
try
{
return this.rsaProvider.Encrypt(data, false);
}
catch (CryptographicException ex)
{
return null;
}
catch (ArgumentNullException ex)
{
return null;
}
}

How to decrypt

The following function explains how to decrypt the data:

 private Byte[] Decrypt(Byte[] dataTodecrypt)
{
try
{
return this.rsaProvider.Decrypt(dataTodecrypt,false);
}
catch (CryptographicException ex)
{
return null;
}
catch (ArgumentNullException ex)
{
return null;
}
}

The second parameter of both Encrypt and Decrypt method of RSACryptoServiceProvider is kept false to use PKCS#1 v1.5 padding; to perform encryption using OAEP padding keep it true. You can convert byte array to string type using the following code:

this.byteConverter.GetString(decryptedData,0,decryptedData.Length)
This page was last modified on 22 April 2013, at 10:31.
402 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved