C# / Windows Phone 7 - AES Encryption on WP7
You may already know that data-in-transit is secured via SSL. When calling a web service, however, the need may arise to encrypt and decrypt data. There are several cryptography algorithms on Windows Phone 7 that are supported, but we are providing a solid sample implementation using a 128-bit block size and 128-bit key size. AESManaged has a fixed block size of 128 bits and a key size of 128, 192, or 256 bits. Also, the Cipher Mode is defaulted to CBC, with a PKCS7 Padding.
Click here to download the source code of an example application that demonstrates encryption and decryption using the above AES class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | class AES { public static byte [] Encrypt ( byte [] data, byte [] key, byte [] iv) { if (data == null || data.Length <= 0) throw new ArgumentNullException( "data" ); if (key == null || key.Length <= 0) throw new ArgumentNullException( "key" ); if (iv == null || iv.Length <= 0) throw new ArgumentNullException( "key" ); byte [] encrypted; using (AesManaged AESM = new AesManaged()) { // Defaults // CipherMode = CBC // Padding = PKCS7 AESM.KeySize = 128; AESM.BlockSize = 128; AESM.Key = key; AESM.IV = iv; ICryptoTransform encryptor = AESM.CreateEncryptor(); encrypted = encryptor.TransformFinalBlock(data, 0, data.Length); } return encrypted; } public static byte [] Decrypt ( byte [] cipherText, byte [] key, byte [] iv) { if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException( "cipherText" ); if (key == null || key.Length <= 0) throw new ArgumentNullException( "key" ); if (iv == null || iv.Length <= 0) throw new ArgumentNullException( "key" ); byte [] decrypted; using (AesManaged AESM = new AesManaged()) { // Defaults // CipherMode = CBC // Padding = PKCS7 AESM.KeySize = 128; AESM.BlockSize = 128; AESM.Key = key; AESM.IV = iv; ICryptoTransform decryptor = AESM.CreateDecryptor(); decrypted = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length); } return decrypted; } } |
Comments