Howdy fellow programmers! I want to allow users of my software to securely transfer information from their Windows Phone devices to a couple of different services in the most convenient, common and platform independent way possible. Preferably with the tools already delivered by Microsoft. For this reason I looked into the AesManaged class that is available through the “System.Security.Cryptography” namespace in the Windows Phone SDK 7.1. However, so far I’m unable to even reproduce a single NIST example with this class. Amongst others I tried the following:
/* http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf page 35 and 36 */
var passwordBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
var unencryptedBytes = new byte[]{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
using (var aes = new AesManaged())
{
aes.BlockSize = 128; /* size in bits */
aes.KeySize = 128; /* size in bits */
aes.Key = passwordBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(unencryptedBytes, 0, unencryptedBytes.Length);
cryptoStream.FlushFinalBlock();
var stream = memoryStream.ToArray();
/*
should be
69-c4-e0-d8-6a-7b-04-30-d8-cd-b7-80-70-b4-c5-5a = 128 bit
according to http://testprotect.com/appendix/AEScalc and fips-197.pdf
*/
var output = BitConverter.ToString(stream);
/*
86-DB-4D-44-72-C0-16-E6-80-B9-D2-B2-3C-6D-00-40-98-4C-59-76-CF-41-DF-4E-A6-46-BB-DE-4C-13-E6-12
256 bit?
*/
}
}
}
I saw a couple of code examples (eg http://msdn.microsoft.com/de-de/library/system.security.cryptography.aesmanaged.aspx) that make use of IV and Rfc2898DeriveBytes (eg http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx), but what is the de-facto standard that is understood by every system by default? What is the default “Key Padding” algorithm and how to use it on a windows phone (maybe https://www.ietf.org/rfc/rfc3394.txt or https://www.ietf.org/rfc/rfc5649.txt ?). And lastely: Can I change the default (CBC according to http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.mode.aspx) to any other Mode on Windows Phone?
What the document fails to point out is that they use all zeros for the Initialization Vector. So set the IV to 16 bytes of all zero and it works:
For your application, you will want to make the IV something other than all zeros. You wont be able to change the Mode using
AesManaged, since AES is implemented using the CBC mode (or ECB). You will get an exception if you try to set it to anything else. You can change the Padding to whatever you like. I would leave it as PKCS7 (the default).