C# RijndaelManaged to Python equivalent
本文关键字:equivalent Python to RijndaelManaged | 更新日期: 2023-09-27 18:11:28
我有以下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')
您应该使用合适的zip文件库。我猜这是特定的格式,是失败的你写声明。使用这个库应该可以避免这样的缺点。
open
函数在被保护的情况下,可以选择密码。