Skip to main content

Using Bouncy Castle on Windows Phone 7

I'm currently working on a port of an application from iPhone onto WP7 and the local content has to be decrypted on the device. The content was original encrypted for a different platform and the cipher & padding used are not supported in the Silverlight version for WP7. The content was encrypted using the AES symmetric algorithm with an ECB cipher and PCKS5 padding. As stated this combination is not supported by the AESManaged  class available in the System.Security.Cryptography namespace. The documentation states only the following is supported:

'The cipher mode is always CBC, and the padding mode is always PKCS7'

I'm not sure why this is, but I'm aware that ECB is no longer viewed a secure cipher - the choice to use this was out of our hands. The next stage was to find OSS library for WP7. After several recommendations we decided to use Bouncy Castle. BC (Bouncy Castle) is a well established cryptography library from the Java world with a port to C#. The don't offer a WP7 specific build so I decided to re-compile for WP7 & WP7.1 - both of these are available for download at the bottom of the post. I used the 1.7 source code with IDEA support, available here.

The only issue to arise was during testing the compiled assembly, the Enum class inside BC didn't like some of the reflection code, specifically throwing exception when attempting to get value from an instance of the FieldInfo class, see below:



 I had to add the following conditional compile statements to get the enum parsing to work as expected. After that everything was groovy:


I probably could have refactored the method completely but I didn't, I'm not overly familiar with the code base. This means if you download and use the binaries below you might well find other issues with the BC code base running on WP7. Make sure you write enough tests to cover all your edge cases!

Shown below is the code I used to decrypt the test data. The BC specific code is highlighted in bold, as you can see setting up the AES cipher is easy and the whole process of decrypting data is handled in 5 lines of code. The 'false' parameter passed to the Init() method defines the cipher as a decrypting cipher, using 'true' would mean it would encrypt.

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Get the encrypted data from the WP7 installation directory
    var stream = Application.GetResourceStream(new Uri("test.data", UriKind.Relative)).Stream;
    var encryptedData = new byte[stream.Length];
    stream.Read(encryptedData, 0, encryptedData.Length);
            
    // encryption key...
    var key = Encoding.UTF8.GetBytes("12345678qwertyui");

    // AES algorthim with ECB cipher & PKCS5 padding...
    var cipher = CipherUtilities.GetCipher("AES/ECB/PKCS5Padding");

    // Initialise the cipher...
    cipher.Init(false, new KeyParameter(key));

    // Decrypt the data and write the 'final' byte stream...
    var bytes = cipher.ProcessBytes(encryptedData);
    var final = cipher.DoFinal();

    // Write the decrypt bytes & final to memory...
    var decryptedStream = new MemoryStream(bytes.Length);
    decryptedStream.Write(bytes, 0, bytes.Length);
    decryptedStream.Write(final, 0, final.Length);
    decryptedStream.Flush();

    var decryptedData = new byte[decryptedStream.Length];
    decryptedStream.Read(decryptedData, 0, (int)decryptedStream.Length);

    // Convert the decrypted data to a string value...
    var result = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
    Debug.WriteLine(result);
}

That pretty much covers where I got to when using Bouncy Castle, I hope this helps someone in the future.







Comments

  1. Thanks a ton for the port!

    It solved Encryption issue i was having due to lack of ASCII Encoding support in Windows Phone.

    But now i ran into Decryption issue when i use AES with PaddedBlockCipher.

    I am getting "last block incomplete in decrption" and at times "pad lock interrupted" exceptions.

    Do you have any idea ?

    ReplyDelete
  2. Sorry I don't have any ideas, I only decrypt data using the above library ports with AES/ECB/PKCS5Padding settings.

    Are you using the same or different?

    ReplyDelete
  3. Hi, your article's useful- thanks.

    Do you mind sharing how you took the Bouncy Castle 1.7 project files and made them compile for Silverlight?
    I was able to use nant as suggested by the docs to re-compile the dll (with some changes here and there). But it is not a Silverlight assembly of course (even though I did turn on the SILVERLIGHT compile define in the build file).

    Did you have to create a separate Silverlight Library project and move files over one by one?

    Thanks.

    ReplyDelete
    Replies
    1. Yes I created a WP7 (Silverlight) project and copied the files across and fixed any compilation errors...

      Delete
  4. Hi,

    Thanks for your article.
    I met a trouble when I tried to encode password.
    The bytes always be null...I'm not sure what happened...
    byte[] bytes = encryptioncipher.ProcessBytes(byteArray);

    Do you mind sharing your project? So I can debug to find out the reason

    The following lines are the code of my function:

    var byteArray = Encoding.UTF8.GetBytes(input);
    var key = Encoding.UTF8.GetBytes(password);
    var encryptioncipher = CipherUtilities.GetCipher("AES/ECB/PKCS5PADDING");
    encryptioncipher.Init(true, new KeyParameter(key));

    //string algo = encryptioncipher.AlgorithmName;
    int blocksize = encryptioncipher.GetBlockSize();

    byte[] bytes = encryptioncipher.ProcessBytes(byteArray);

    byte[] final = encryptioncipher.DoFinal();

    //string resultBytes = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    MemoryStream encryptedstream = new MemoryStream(final.Length);
    //encryptedstream.Write(bytes, 0, bytes.Length);
    encryptedstream.Write(final, 0, final.Length);
    encryptedstream.Flush();

    byte[] encryptedData = new byte[encryptedstream.Length];
    encryptedstream.Position = 0;
    encryptedstream.Read(encryptedData, 0, encryptedData.Length);

    ReplyDelete
  5. I'm using bouncy castle to decrypt message from server RSA encrypted with 1024 bit key. I have key in pem file. When i try to read pem file with Org.BouncyCastle.OpenSsl.PemReader.ReadObject() it throws TypeInitializationException. Help i can't understand what i'm doing wrong. The code is

    StreamResourceInfo ResourceStream = Application.GetResourceStream(new Uri("Resources/public.pem", UriKind.Relative));
    StreamReader streamReader = new StreamReader(ResourceStream.Stream);
    PemReader pr = new PemReader(streamReader );
    AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();

    ReplyDelete
  6. Hi there. This sounds like what I need but I am fairly new to the whole encrypt/decrypt thing. I've tried implementing and I'm getting an exception when assigning the cipher.DoFinal to final. Exception is "last block incomplete decryption". I've searched for non WP7 answers but they don't seem to be helping. I'm a bit confused what the doFinal method does.

    Any help would be great.

    Thanks,

    G

    ReplyDelete
  7. Hi I am very new to Bouncy castle.

    I want to generate Signature and verify signature.
    Can you please provide me a sample code for that

    ReplyDelete
  8. Hi,
    I'm trying to use your dll with "AES/CBC/NoPadding" to decrypt from PHP but I got always \0 characters.
    this is my code:

    private static string myDecrypt(string cipherText)
    {
    // encryption key...
    var key = Encoding.UTF8.GetBytes("MyKey");
    var iv = Encoding.UTF8.GetBytes("MyIV");

    var cipher = CipherUtilities.GetCipher("AES/CBC/NoPadding");
    ParametersWithIV par = new ParametersWithIV(new KeyParameter(key), iv);

    // Initialise the cipher...
    cipher.Init(false, par);
    var bytes = cipher.DoFinal(Encoding.UTF8.GetBytes(cipherText));
    string result = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    //result is Always \0\0\0\0\0\0\0\0\0\0\0....
    return result;
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v...

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example ...

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most ...