低于python的C#字节数组长度

时间:2018-08-29 16:44:00

标签: c# python byte

我正在尝试将一些Python代码移植到C#,并且在代码中有一部分使用以下密钥使用AES加密了字符串:

  

'\ xd7 \ xdf \ xca2 \ xd0Vhu \ xeb \ x06 \ xa0 \ xba \ n \ xa2 \ x07O \ xc1 \ x8b \ xcf \ x8f2&t \ xc0 \ x92 \ xc4 \ xa5 \ x0b> \ xb4 \ xe7 \ xbc'

此密钥在Python中为32字节,但问题是在C#中,当我转换该字符串(Encoding.Default.GetBytes)时为30字节,因此我无法生成AES密钥。

为什么在Python中键的长度为32,而在C#中字节数组的长度为何为30?

将密钥转换为字节数组:

byte[] key = Encoding.Default.GetBytes("\xd7\xdf\xca2\xd0Vhu\xeb\x06\xa0\xba\n\xa2\x07O\xc1\x8b\xcf\x8f2&t\xc0\x92\xc4\xa5\x0b>\xb4\xe7\xbc");

为算法异常获取无效的密钥大小(因为它是30个字节而不是32个字节):

byte[] encrypted;
byte[] iv;
using (Aes aesAlg = Aes.Create())
{
    aesAlg.Key = key;
    aesAlg.GenerateIV();
    iv = aesAlg.IV;
    aesAlg.Mode = CipherMode.CBC;

    var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, iv);

    using (var msEncrypt = new MemoryStream())
    {
        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        {
            using (var swEncrypt = new StreamWriter(csEncrypt))
            {
                swEncrypt.Write("test");
            }
            encrypted = msEncrypt.ToArray();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您拥有的字节字符串是一种混合编码,带有unicode码点和字符的ASCII表示形式。您可以在几个地方看到它,

  

'\ xd7 \ xdf \ xca 2 \ xd0 Vhu \ xeb \ x06 \ xa0 \ xba \ n \ xa2 \ x07 < strong> O \ xc1 \ x8b \ xcf \ x8f 2&t \ xc0 \ x92 \ xc4 \ xa5 \ x0b > \ xb4 \ xe7 \ xbc'

如果将这些转换为代码点,则会以"\xd7\xdf\xca\x32\xd0\x56\x68\x75\xeb\x06\xa0\xba\x0a\xa2\x07\x4f\xc1\x8b\xcf\x8f\x32\x26\x74\xc0\x92\xc4\xa5\x0b\x3e\xb4\xe7\xbc"结尾,并且应该具有正确的密钥字节。

var val = "\xd7\xdf\xca\x32\xd0\x56\x68\x75\xeb\x06\xa0\xba\x0a\xa2\x07\x4f\xc1\x8b\xcf\x8f\x32\x26\x74\xc0\x92\xc4\xa5\x0b\x3e\xb4\xe7\xbc";
var count = Encoding.Default.GetByteCount(val);
Console.WriteLine(count); // 32