使用AES/CBC/NoPadding将C#转换为Python [英] Convert C# to Python using AES/CBC/NoPadding

查看:197
本文介绍了使用AES/CBC/NoPadding将C#转换为Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此C#代码转换为Python(2.7).问题是python的解密结果是错误的. IV和密钥正确.

I'm trying to convert this C# code to Python (2.7). The problem is that the result of the decryption is wrong with the python code. IV and key is correct.

我找到了许多谈论Python和C#的主题,但没有找到答案.

I found many subjects that talk about Python and C# but i didn't found an answer.

C#加密:

class Tracer
{
    private static readonly int BlockBitSize = 128;
    private static readonly int KeyBitSize = 256;

    internal static byte[] In(byte[] plainBytes, byte[] uid)
    {
        using (var sha = new SHA512Managed())
        {
            var hash = sha.ComputeHash(uid);
            return In(plainBytes, hash.Skip(32).Take(32).ToArray(), hash.Take(16).ToArray());
        }
    }

    internal static byte[] In(byte[] plainBytes, byte[] key, byte[] iv)
    {
        if (key == null || key.Length != KeyBitSize / 8)
            throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
        if (iv == null || iv.Length != BlockBitSize / 8)
            throw new ArgumentException(String.Format("IV needs to be {0} bit!", BlockBitSize), "iv");

        using (AesManaged aes = new AesManaged())
        {
            aes.KeySize = KeyBitSize;
            aes.BlockSize = BlockBitSize;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;

            using (ICryptoTransform encrypter = aes.CreateEncryptor(key, iv))
                using (MemoryStream cipherStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                        cryptoStream.FlushFinalBlock();
                    }
                    return cipherStream.ToArray();
                }
        }
    }

    internal static byte[] Out(byte[] cipherBytes, byte[] uid)
    {
        using (var sha = new SHA512Managed())
        {
            var hash = sha.ComputeHash(uid);
            return Out(cipherBytes, hash.Skip(32).Take(32).ToArray(), hash.Take(16).ToArray());
        }
    }

    internal static byte[] Out(byte[] cipherBytes, byte[] key, byte[] iv)
    {
        if (key == null || key.Length != KeyBitSize / 8)
            throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
        if (iv == null || iv.Length != BlockBitSize / 8)
            throw new ArgumentException(String.Format("IV needs to be {0} bit!", BlockBitSize), "iv");

        using (AesManaged aes = new AesManaged())
        {
            aes.KeySize = KeyBitSize;
            aes.BlockSize = BlockBitSize;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;

            using (ICryptoTransform decrypter = aes.CreateDecryptor(key, iv))
                using (MemoryStream plainStream = new MemoryStream())
                {
                    using (var decrypterStream = new CryptoStream(plainStream, decrypter, CryptoStreamMode.Write))
                        using (var binaryWriter = new BinaryWriter(decrypterStream))
                        {
                            //Decrypt Cipher Text from Message
                            binaryWriter.Write(cipherBytes, 0, cipherBytes.Length);
                        }
                    //Return Plain Text
                    return plainStream.ToArray();
                }
        }
    }
}

Python解密

def AESdecrypt(ciphertext, UID):

    from Crypto.Cipher import AES

    digest = hashlib.sha512(UID).hexdigest()

    iv = BitArray(hex=digest[:32])

    key = BitArray(hex=digest[64:128])

    block40Str = BitArray(hex=ciphertext[1].encode('hex'))

    cipherSpec = AES.new(key.bytes, AES.MODE_CBC, iv.bytes)
    plaintextWithPadding = cipherSpec.decrypt(block40Str.bytes)

注意:对不起,我的英语水平

Note : Sorry for my english

感谢您的帮助!

Python中的AES解密返回64个字符,这是错误的.原始明文是32.

EDIT : AES decryption in Python return 64 characters, that is wrong. The original plaintext is 32.

Python代码已更新.解密函数现在返回32个字符,但仍然做错了

Python code updated. The decrypt function return now 32 characters, but still doing wrong

推荐答案

用于生成密钥的摘要和iv是使用正确的数据但以字符串形式生成的.相反,C#使用数据的ByteArray生成摘要.感谢 BitArray Python库,我解决了我的问题:

The digest used to generate the key and the iv was generated with the correct data but in string. Conversely, C# generate the digest with a ByteArray of the data. Thanks to the BitArray Python library , i solve my problem :

新的Python代码:

def AESdecrypt(ciphertext, UID):

    from Crypto.Cipher import AES

    UIDBytes = BitArray(hex=UID)
    digest = hashlib.sha512(UIDBytes.bytes).hexdigest()

    iv = BitArray(hex=digest[:32])

    key = BitArray(hex=digest[64:128])

    cipherSpec = AES.new(key.bytes, AES.MODE_CBC, iv.bytes)
    plaintextWithoutPadding = cipherSpec.decrypt(ciphertext[1])

这篇关于使用AES/CBC/NoPadding将C#转换为Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆