Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte arrays to base64 string

Say I have two byte arrays.

In the first scenario, I concatenate the two arrays (using Buffer.BlockCopy), then convert the result to base64 string.

In the second scenario, I convert each byte array into base64 string and then concatenate those strings.

Would the two results be the same?

like image 631
Alex K Avatar asked Oct 08 '16 01:10

Alex K


2 Answers

Results would be the same if length of the first array is divisible by 3, in all other cases result of concatenation of two base64 strings would be different (and invalid base64) due to padding bytes at the end of first string. Length of second array does not matter for this operation as padding is always at the end.

Why "divisible by 3" - since base64 encodes every 3 bytes into exactly 4 characters arrays of such length will not need padding at the end. See https://www.rfc-editor.org/rfc/rfc4648#section-4 for formal details and https://en.wikipedia.org/wiki/Base64#Padding for more readable explanation.

I.e. if first array is 4 bytes long you get == at the end of converted string and concatenation with other base64 string will result in invalid base64 text

Convert.ToBase64String(new byte[]{1,2,3,4}) // AQIDBA==

Sample case where concatenation works the same on arrays first or on strings:

 Convert.ToBase64String(new byte[]{1,2,3}) + // length divisible by 3
 Convert.ToBase64String(new byte[]{4,5}) 
 == 
 Convert.ToBase64String(new byte[]{1,2,3,4,5}) // AQIDBAU=
like image 72
Alexei Levenkov Avatar answered Oct 17 '22 14:10

Alexei Levenkov


void Main()
{
    byte[] bytes1 = new byte[]{10, 20, 30, 40, 0, 0, 0, 0};
    byte[] bytes2 = new byte[]{50, 60, 70, 80};

    Buffer.BlockCopy(bytes2, 0, bytes1, 4, 4);

    PrintByteArray(bytes1);

    string bytesStr = Convert.ToBase64String(bytes1);
    Console.WriteLine(bytesStr);

    string bytesStr1 = Convert.ToBase64String(bytes1);
    string bytesStr2 = Convert.ToBase64String(bytes2);

    string bytesStrMerged = bytesStr1 + bytesStr2;
    Console.WriteLine(bytesStrMerged);
}


public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder();
    foreach (var b in bytes)
    {
        sb.Append(b + " ");
    }
    Console.WriteLine(sb.ToString());
}

Outputs:

10 20 30 40 50 60 70 80 
ChQeKDI8RlA=
ChQeKDI8RlA=MjxGUA==
like image 27
Miguel Sanchez Avatar answered Oct 17 '22 16:10

Miguel Sanchez