I using this class to perform AES encryption/decryption:
class Aes { static byte[] Key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; static byte[] IV = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static byte[] Encrypt(string plainText) { byte[] encrypted; // Create a new AesManaged. using (AesManaged aes = new AesManaged()) { aes.Padding = PaddingMode.None; aes.Mode = CipherMode.ECB; // Create encryptor ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV); // Create MemoryStream using (MemoryStream ms = new MemoryStream()) { // Create crypto stream using the CryptoStream class. This class is the key to encryption // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream // to encrypt using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // Create StreamWriter and write data to a stream using (StreamWriter sw = new StreamWriter(cs)) sw.Write(plainText); encrypted = ms.ToArray(); } } } // Return encrypted data return encrypted; } public static string Decrypt(byte[] cipherText/*, byte[] Key=Key, byte[] IV=IV*/) { string plaintext = null; // Create AesManaged using (AesManaged aes = new AesManaged()) { aes.Padding = PaddingMode.None; aes.Mode = CipherMode.ECB; // Create a decryptor ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV); // Create the streams used for decryption. using (MemoryStream ms = new MemoryStream(cipherText)) { // Create crypto stream using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { // Read crypto stream using (StreamReader reader = new StreamReader(cs)) plaintext = reader.ReadToEnd(); } } } return plaintext; } } The problem is that when I encrypt using the following code I get the error: System.Security.Cryptography.CryptographicException: 'Length of the data to encrypt is invalid.'
var x = Aes.Encrypt(System.Text.Encoding.Default.GetString(new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff })); Console.WriteLine(string.Join(", ", x.Select(b => b.ToString("X2")))); I am trying to implement encrypted communication with a MSP432 microcontroller. According to this example, using these values:
Key: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f Plaintext: 00112233445566778899aabbccddeeff I should get:
Ciphertext: 8ea2b7ca516745bfeafc49904b496089 Can someone tell me what I am doing wrong?
PaddingMode.Nonemeans apply no padding, I'll deal with myself. So what will happen noew if you don't have multiple of 16-byte?