在.NET中使用AES-256算法加密文件,然后在python3.6中解密文件

时间:2019-05-02 09:12:46

标签: python .net encryption character-encoding aes

我已经在.NET中使用AES算法对pdf文件进行了加密,但是当我在python中进行处理时,我无法对其正确解密。我需要此管道来满足我的业务需求。解密后的文件与原始文件匹配,但是由于原始文件未写入磁盘,因此与原始文件相比有一些非常小的更改。我正在为.NET和Python附加代码,并且还输出二进制文件。请帮助您识别现有错误。

我试图用ascii,utf-8和base64对输出进行编码和解码,但没有任何帮助。只需稍稍更改编码即可为我完成工作。

.NET CODE进行加密/解密
static AES()
        {
            aesManaged = new AesManaged();
            encryptor = aesManaged.CreateEncryptor(key, iv);
            decryptor = aesManaged.CreateDecryptor(key, iv);
        }

        public static byte[] Transform(byte[] inputBuf, bool decrypt)
        {
            byte[] outArray = new byte[] { };

            using (AesManaged aesManaged = new AesManaged())
            {
                if (decrypt)
                {
                    #region Decryption
                    outArray = decryptor.TransformFinalBlock(inputBuf, 0, inputBuf.Length);

                    return outArray;
                    #endregion
                }
                else
                {
                    #region Encryption
                    outArray = encryptor.TransformFinalBlock(inputBuf, 0, inputBuf.Length);

                    return outArray;
                    #endregion
                }
            }
        }


        public static void Transform(string inputPath, string outputPath, bool decrypt = false)
        {
            int numRead = 0;
            const int BUF_SIZE = 1024;

            byte[] buf = new byte[BUF_SIZE];

            using (FileStream fs = new FileStream(inputPath, FileMode.Open, FileAccess.Read))
            {
                using (BinaryWriter binWriter = new BinaryWriter(new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)))
                {
                    while((numRead = fs.Read(buf, 0, BUF_SIZE)) > 0)
                    {
                        byte[] transformed = Transform(buf, decrypt);

                        binWriter.Write(transformed);
                    }
                }
            }
        }

用于解密同一文件的python3.6代码

def decrypt(in_filename, chunksize=1024):
    out_filename = 'newDecoded.pdf'
    private_key = key_orginal
    with open(in_filename, 'rb') as infile:
        cipher = AES.new(private_key, AES.MODE_CBC, iv)
        with open(out_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                #chunk = infile.read()
                print(sys.getsizeof(chunk))
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += 16 - len(chunk) % 16
                #decoded = base64.b64decode(chunk)
                #print(sys.getsizeof(decoded))
                text = cipher.decrypt(chunk)
                print(text)
                outfile.write(text)
    print('Done')

0 个答案:

没有答案