Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad byte[] to 16-byte multiple for AES Encryption

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.

like image 203
WB3000 Avatar asked Dec 17 '22 07:12

WB3000


1 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);
}
like image 97
plinth Avatar answered Dec 31 '22 14:12

plinth