字符串到字节数组(到字符串到 XML)并再次返回

Ale*_*lex 2 c# string bytearray type-conversion

我知道有 100 万个关于“字符串 - 字节数组”转换的问题,但没有一个适合我的问题。

为了安装我的软件,我需要保存用户的一些信息(服务器地址、用户 ID、密码等)。其中一些信息需要受到保护(使用 DPAPI 加密)。为此,我必须将string( SecureString)转换为byte[]

public static byte[] StringToByte(string s)
{
    return Convert.FromBase64String(s);
}
Run Code Online (Sandbox Code Playgroud)

我遇到的第一个问题。如果字符串长度不是 4 ( s.lenght % 4 == 0)的倍数,我会收到“Base-64 字符数组的长度无效”错误。我读过我可以(必须)在末尾添加“=”,string但其中一些字符串可能是密码(可能包含“=”)。我需要将(加密的)数据存储在 XML 文件中,为什么我不能使用 Unicode 编码(我不知道为什么,但它破坏了 XML 文件......因为我认为是编码)。

作为最后一步,我必须回到在应用程序启动时获取存储数据的方法。

你们中有人可以帮我解决这个问题吗?我不在乎 XML 中的输出,只要它是“可读的”。

最好的问候亚历克斯

Jon*_*eet 7

我遇到的第一个问题。如果字符串长度不是 4 的倍数(s.lenght % 4 == 0),我会收到“Base-64 字符数组的长度无效”错误。

这表明它不是 base64 开始。听起来您在这里走错了方向 - base64 用于将二进制数据转换为文本。要将文本转换为二进制形式,您通常应该使用Encoding.GetBytes

return Encoding.UTF8.GetBytes(text);
Run Code Online (Sandbox Code Playgroud)

现在,如果您需要将加密结果(将是二进制数据)编码为文本,那么您将使用 base64。(因为对 UTF-8 编码的文本进行加密的结果不是UTF-8 编码的文本。)

所以像:

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);
}
Run Code Online (Sandbox Code Playgroud)