.Net 中的文件加密和 Python 中的解密 | AES加密

时间:2021-04-10 14:32:57

标签: python .net encryption

大家好,我正在尝试在 .Net 中加密并在 Python 中解密。 我试过这样做,我可以在 .Net 中加密,但是在 python 中解密时我遇到了一些错误。 我是新手,很抱歉我的编码不好。

这里是 .Net 中的加密

public static void Main(string[] args)
    {
    

        try
        {
            using FileStream myStream = new FileStream("file.pdf", FileMode.OpenOrCreate);
  
            using Aes aes = Aes.Create();
            var textencoder = new System.Text.UTF8Encoding();

            aes.Key = textencoder.GetBytes('16bytesEncryption');
            aes.IV = textencoder.GetBytes('1234567812345678');
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            byte[] iv = aes.IV;
            myStream.Write(iv, 0, iv.Length);
 
            using CryptoStream cryptStream = new CryptoStream(
                myStream, 
                aes.CreateEncryptor(),
                CryptoStreamMode.Write);
 
    
            sWriter.WriteLine("Hello World!");

            cryptStream.FlushFinalBlock();

         
            Console.WriteLine("The file was encrypted.");
        }
        catch
        {
      
            Console.WriteLine("The encryption failed.");
            throw;
        }
    }


这里是 Python 中的解密


key = b'16bytesEncryption'
iv = b'1234567812345678'


with open('file.pdf','rb') as fin:
    fsz = struct.unpack('<Q', fin.read(struct.calcsize('<Q')))[0]

    aes = AES.new(key, AES.MODE_CBC, iv)

    with open("outfile.pdf", 'wb+') as fout:
        while True:
            data = fin.read(16)
            n = len(data)
            if n == 0:
                break
            decd = aes.decrypt(data) #<---Error on this line
            n = len(decd)
            if fsz > n:
                fout.write(decd)
         

解密时出错->

Traceback (most recent call last):
File "C:/Users/Lenovo/PycharmProjects/pythonProject/demo.py",line 18, in <module>
desc = aes.decrypt(data)

File "C:\Users/Lenovo\PycharmProjects\pythonProject\venu\lib\site-packages\Crypto\Cipher\_ mode_cbc.py", raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block size) 
ValueError: Data must be padded to 16 byte boundary in CBC mode

Process finished with exit code 1

0 个答案:

没有答案
相关问题