将 C# 转换为 Python base64 编码

Converting C# to Python base64 encoding

我正在尝试将函数从 C# 转换为 python。

我的 C# 代码:

static string Base64Encode(string plainText)
{
    char[] arr = plainText.ToCharArray();
    List<byte> code16 = new List<byte>();
    int i = 1;
    string note = "";
    foreach (char row in arr)
    {
        if (i == 1)
        {
            note += "0x" + row;
        }
        else if (i == 2)
        {
            note += row;
            code16.Add(Convert.ToByte(note, 16));
            note = "";
            i = 0;
        }

        i++;
    }
    return System.Convert.ToBase64String(code16.ToArray());
}

我的Python代码:

def Base64Ecode(plainText):
    code16 = []
    i = 1
    note = ''
    for row in plainText:
        if i == 1:
            note += '0x' + row
        elif i == 2:
            note += row
            code16.append(int(note, 16))
            note = ''
            i = 0
        i += 1
    test = ''
    for blah in code16:
        test += chr(blah)

    print(base64.b64encode(test.encode()))

两个 code16 值相同,但我在尝试 base64 编码数据时遇到问题。 C# 采用字节数组,但 pyton 采用字符串,我得到两个不同的结果。

string.encode() 默认使用 utf-8 编码,这可能会创建一些您不想要的 multi-byte 字符。

使用 string.encode("latin1") 创建从 00FF 的字节。

也就是说,python 中有一个更简单的方法可以将 Hex-String 转换为字节数组(或字节对象):

base64.b64encode(bytes.fromhex(plainText))

给出与您的函数相同的结果。