How to convert string to base64 byte array, would this be valid?

71,133

Solution 1

Looks okay, although the approach is strange. But use Encoding.ASCII.GetBytes() to convert the base64 string to byte[]. Base64 encoding only contains ASCII characters. Using Unicode gets you an extra 0 byte for each character.

Solution 2

You can use:

From byte[] to string:

byte[] array = somebytearray;

string result = Convert.ToBase64String(array);

From string to byte[]:

array = Convert.FromBase64String(result);

Solution 3

Representing a string as a blob represented as a string is odd... any reason you can't just use the string directly?

The string is always unicode; it is the encoded bytes that change. Since base-64 is always <128, using unicode in the last part seems overkill (unless that is what the wire-format demands). Personally, I'd use UTF8 or ASCII for the last GetBytes so that each base-64 character only takes one byte.

Share:
71,133
anumsadiq
Author by

anumsadiq

Updated on May 19, 2020

Comments

  • anumsadiq
    anumsadiq almost 4 years

    I'm trying to write a function that converts a string to a base64 byte array. I've tried with this approach:

    public byte[] stringToBase64ByteArray(String input)
    {
        byte[] ret = System.Text.Encoding.Unicode.GetBytes(input);
        string s = Convert.ToBase64String(input);
        ret = System.Text.Encoding.Unicode.GetBytes(s);
        return ret;
    }
    

    Would this function produce a valid result (provided that the string is in unicode)? Thanks!