Alex
Alex

Reputation: 1947

string to byte array (to string to XML) and back again

i know there are 1million questions about "string - byte array" conversion out there but none of them fit my problem.

For the installation of my software i need to save some informations from the user (serveraddress, userID, password and so on). Some of these informations need do be protected (encrypted using DPAPI). For that i have to convert the string (SecureString) to byte[]

public static byte[] StringToByte(string s)
{
    return Convert.FromBase64String(s);
}

where i get my first problem. If the strings lenght is a not a multiple of 4 (s.lenght % 4 == 0) i get a "Invalid length for a Base-64 char array" error. I've read that i can (have to) add "=" to the end of the string but some of these strings may be passwords (which may contain "="). I need to store the (encrypted) data in a XML-file why i can't use Unicode encoding (i don't know why but it corrupts the XML file ... because of encoding i would suppose).

As last step i have to go back the way to get the stored data on app startup.

Does someone of you can help me solving this problem ? I don't care the output in the XML as long as it is "readable".

best regards Alex

Upvotes: 2

Views: 13269

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500405

where i get my first problem. If the strings lenght is a not a multiple of 4 (s.lenght % 4 == 0) i get a "Invalid length for a Base-64 char array" error.

That suggests that it's not base64 to start with. It sounds like you're going in the wrong direction here - base64 is used to convert binary data into text. To convert text into a binary form, you should normally just use Encoding.GetBytes:

return Encoding.UTF8.GetBytes(text);

Now if you needed to encode the result of the encryption (which will be binary data) as text, then you'd use base64. (Because the result of encrypting UTF-8-encoded text is not UTF-8-encoded text.)

So something like:

public static string EncryptText(string input)
{
    byte[] unencryptedBytes = Encoding.UTF8.GetBytes(input);
    byte[] encryptedBytes = EncryptBytes(unencryptedBytes); // Not shown here
    return Convert.ToBase64String(encryptedBytes);
}

public static string DecryptText(string input)
{
    byte[] encryptedBytes = Convert.FromBase64String(input);
    byte[] unencryptedBytes = DecryptBytes(encryptedBytes); // Not shown here
    return Encoding.UTF8.GetString(unencryptedBytes);
}

Upvotes: 7

Related Questions