编程语言
首页 > 编程语言> > C#Rijndael管理等效于Python

C#Rijndael管理等效于Python

作者:互联网

我有以下C#代码(代码是继承的,无法编译).这用于解密和解压缩保存的文件.

using System.Security.Cryptography;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

//Not the real key but same amount of chars
private const string kEncyptionKey = "01234567";

public string DecryptAndDecompressText (string strFileName)
{
    // Decryption ///
    FileStream fin = null;
    try
    {
        fin = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
    }
    catch (System.IO.FileNotFoundException)
    {
        return "";
    }

    MemoryStream    memoryToDecompress =  new MemoryStream();

    UnicodeEncoding UE       = new UnicodeEncoding();
    RijndaelManaged RMCrypto = new RijndaelManaged();

    // This is the encryption key for our file 
    byte[] key = UE.GetBytes(kEncyptionKey);

    // Decrypt the data to a stream
    CryptoStream cs = new CryptoStream( memoryToDecompress, 
                                        RMCrypto.CreateDecryptor(key, key),
                                        CryptoStreamMode.Write);
    byte [] fileBuffer = new byte[fin.Length];
    fin.Read(fileBuffer, 0, fileBuffer.Length);
    cs.Write(fileBuffer, 0, fileBuffer.Length);

    fin.Close();

    // Reset the index of the Memory Stream
    memoryToDecompress.Position = 0;

    // Let the GC clean this up, we still need the memory stream
    //cs.Close();   


    // Decompress the File
    ZipInputStream s;
    s = new ZipInputStream(memoryToDecompress);

    ZipEntry theEntry;
    try
    {
        theEntry = s.GetNextEntry();
    }
    catch (System.Exception)
    {
        // Could not open the file...
        return "";
    }
}

我正在尝试创建一个python程序来执行相同的操作.这就是我得到的:

from Crypto.Cipher import AES

KEY = '01234567'.encode('utf-16be')

_f = open('<file>', 'r')

 _content = _f.read()

_cipher = AES.new(KEY, AES.MODE_CBC, KEY)

_dcontent = _cipher.decrypt(_content)

with open('extract.zip', 'w') as newfile:
    newfile.write(_dcontent)

_f.close()

我将结果写入磁盘,因为我希望它是一个zip文件(包含一个文件).但是,我无法使用存档管理器打开文件.

欢迎任何建议!

解决方法:

您必须使用相同的密钥. System.Text.UnicodeEncoding是UTF-16le编码,在python中也具有等效功能:

KEY = '01234567'.encode('utf-16le')

如果您使用的是Windows,则必须以二进制模式读写文件:

_f = open('<file>', 'rb')
...
open('extract.zip', 'wb')

标签:rijndael,aes,python,c
来源: https://codeday.me/bug/20191119/2038659.html