views:

569

answers:

3

I currently have a function [C#] which takes a byte[] and an alignment to set it to, but during encryption, an error is thrown every once in awhile.

    private byte[] AlignByteArray(byte[] content, int alignto)
    {
        long thelength = content.Length - 1;
        long remainder = 1;

        while (remainder != 0)
        {
            thelength += 1;
            remainder = thelength % alignto;
        }
        Array.Resize(ref content, (int)thelength);
        return content;
    }

Does anyone see any issues with the function? I'm getting errors that the content size is not valid during AES encryption, suggesting that it is not padding right.

A: 

Why do you set remainder = 1 instead of checking what the actual remainder is before the while loop?

Donnie DeBoer
+1  A: 

Are you sure it's 0x16 and not 16? (I thought it was 16 so I'm assuming that).

Edit: Any decent compiler should turn (x / 16) into (x >> 4).

int length = 16 * ((content.Length + 15) / 16);
Array.Resize(ref content, length);

Edit 2: For general purpose:

int length = alignment * ((content.Length + alignment - 1) / alignment);
Array.Resize(ref content, length);
280Z28
+2  A: 

Here's a simple solution:

private static void PadToMultipleOf(byte[] src, int pad)
{
    int len = (src.Length + pad - 1) / pad * pad;
    Array.Resize(ref src, len);
}
plinth