Pad byte [] up to 16 bytes for AES Encryption

I currently have a function [C #] that takes byte [] and alignment to set it, but during encryption an error is called every time after some time.

    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 problems with this feature? I get errors that the size of the content is invalid during AES encryption, assuming that it is not padded correctly.

+3
source share
2 answers

Here's a simple solution:

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

Are you sure this is 0x16, not 16? (I thought I was 16, so I guess).

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

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

2: :

int length = alignment * ((content.Length + alignment - 1) / alignment);
Array.Resize(ref content, length);
+1

Source: https://habr.com/ru/post/1712889/


All Articles