gpt4 book ai didi

C# RijndaelManaged 相当于 Python

转载 作者:行者123 更新时间:2023-11-28 16:30:32 26 4
gpt4 key购买 nike

我有以下 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 文件(其中包含一个文件)。但是我无法使用存档管理器打开文件。

欢迎提出任何建议!

最佳答案

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

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

如果您在 Windows 上,则必须以二进制模式读写文件:

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

关于C# RijndaelManaged 相当于 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com