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.
That pretty much covers where I got to when using Bouncy Castle, I hope this helps someone in the future.
'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.
Thanks a ton for the port!
ReplyDeleteIt 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 ?
Sorry I don't have any ideas, I only decrypt data using the above library ports with AES/ECB/PKCS5Padding settings.
ReplyDeleteAre you using the same or different?
Hi, your article's useful- thanks.
ReplyDeleteDo 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.
Yes I created a WP7 (Silverlight) project and copied the files across and fixed any compilation errors...
DeleteHi,
ReplyDeleteThanks 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);
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
ReplyDeleteStreamResourceInfo 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();
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.
ReplyDeleteAny help would be great.
Thanks,
G
Hi I am very new to Bouncy castle.
ReplyDeleteI want to generate Signature and verify signature.
Can you please provide me a sample code for that
Hi,
ReplyDeleteI'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;
}