1

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?

Cristian M
  • 195
  • 1
  • 1
  • 15
  • This code worked for me in .NET Core. What .NET are you using? – ingvar Aug 17 '19 at 20:13
  • @ingvar I'm using .NET framework 4.6.1. – Cristian M Aug 17 '19 at 20:25
  • @kelalaka Sorry, it does not work for me. – Cristian M Aug 17 '19 at 20:25
  • 1
    ECB mode does not require IV, though that is insecure to use. When your data size is not multiple of 16-byte you need a padding scheme as PKCS#7. `PaddingMode.None` means apply no padding, I'll deal with myself. So what will happen noew if you don't have multiple of 16-byte? – kelalaka Aug 17 '19 at 20:28
  • @kelalaka Using PKCS#7 and 15 bytes of plaintext, there is no error, but I need to obtain the values I mentioned in the question. – Cristian M Aug 17 '19 at 20:31
  • How you enter the plaintext? It is not clear here. – kelalaka Aug 17 '19 at 20:34
  • @kelalaka This is the plaintext: System.Text.Encoding.Default.GetString(new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }) – Cristian M Aug 17 '19 at 20:40
  • You should write as [byte array](https://stackoverflow.com/q/19391073/1820553). – kelalaka Aug 17 '19 at 20:45
  • @kelalaka Thanks for the suggestion. I've replaced string plaintext with byte[] plaintext in the method definition. Using PKCS#7, I know get 16 encrypted bytes (which is OK), but they are not equal to ciphertext I am trying to obtain. If I use padding None, I get the same error. – Cristian M Aug 17 '19 at 21:04
  • @kelalaka The output is BE 89 27 A1 7A 7B E3 2F AC 8A A6 FE 57 B2 84 91 – Cristian M Aug 17 '19 at 21:09
  • I've misunderstood some part, sorry. When you use `ECB` and `no padding` with 16-byte input you should fine. The expected result is ok. Test [here](http://aes.online-domain-tools.com/) and use hex. – kelalaka Aug 17 '19 at 21:37
  • Don’t save off `encrypted` until after you close the CryptoStream. – bartonjs Aug 17 '19 at 21:59
  • @kelalaka I confirm that the website gives the expected results, but when I run my code with no padding and the 16-byte input plaintext given in the question description, I get the same error on the line sw.Write(plainText). What am I missing here? – Cristian M Aug 19 '19 at 07:54
  • make sure that the plaintext is 16-bytes. – kelalaka Aug 19 '19 at 07:57
  • @kelalaka It is. I even verified using this line System.Console.WriteLine(plainText.Length), before using (StreamWriter sw = new StreamWriter(cs). It shows 16 bytes and that is why I am so dazzled about this issue. – Cristian M Aug 19 '19 at 08:08
  • @kelalaka I managed to get it working using this code [link](https://stackoverflow.com/a/24963085/9194851). However, I do not know what is wrong with the initial code. – Cristian M Aug 19 '19 at 13:17
  • Good. If you have time, dig it more. If you find the answer post it and warn me. – kelalaka Aug 19 '19 at 18:11

1 Answers1

0

I managed to get it working using the following code:

 public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)  
         {  
           AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();  
           //Block size : Gets or sets the block size, in bits, of the cryptographic operation.  
           dataencrypt.BlockSize = 128;  
           //KeySize: Gets or sets the size, in bits, of the secret key  
           dataencrypt.KeySize = 128;  
           //Key: Gets or sets the symmetric key that is used for encryption and decryption.  
           dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
           //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm  
           dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
           //Padding: Gets or sets the padding mode used in the symmetric algorithm  
           dataencrypt.Padding = PaddingMode.PKCS7;  
           //Mode: Gets or sets the mode for operation of the symmetric algorithm  
           dataencrypt.Mode = CipherMode.CBC;  
           //Creates a symmetric AES encryptor object using the current key and initialization vector (IV).  
           ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);  
           //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.   
           //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of   
           //information returned at the end might be larger than a single block when padding is added.  
           byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);  
           crypto1.Dispose();  
           //return the encrypted data  
           return encrypteddata;  
         }  

//code to decrypt data
    private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)  
     {  

       AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();  
       keydecrypt.BlockSize = 128;  
       keydecrypt.KeySize = 128;  
       keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       keydecrypt.Padding = PaddingMode.PKCS7;  
       keydecrypt.Mode = CipherMode.CBC;  
       ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);  

       byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);  
       crypto1.Dispose();  
       return returnbytearray;  
     }
Cristian M
  • 195
  • 1
  • 1
  • 15