[英]converting the C# code to python on decryption
using System.Security.Cryptography;
public Task<byte[]> Decrypt(byte[] encryptedBytes, string encryptionKey)
{
if (encryptedBytes == null)
throw new ArgumentNullException("encryptedBytes can't be null");
if (string.IsNullOrEmpty(encryptionKey))
throw new ArgumentNullException("encryptionKey can't be null");
byte[] encryptedTextBytes = encryptedBytes;
this._encryptionKey = encryptionKey;
var encryptionKeyBytes = Encoding.UTF32.GetBytes(this._encryptionKey);
Rfc2898DeriveBytes generatedKey = new Rfc2898DeriveBytes(this._encryptionKey, new byte[] { 0x65, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x65 });
var sessionKey = generatedKey.GetBytes(32);
var iV = generatedKey.GetBytes(16);
return Task.Run(() =>
{
return (Decrypt(encryptedTextBytes, sessionKey, iV));
});
}
public byte[] Decrypt(byte[] dataToDecrypt, byte[] key, byte[] iv)
{
using (var aes = new AesCryptoServiceProvider())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = key;
aes.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write);
cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);
cryptoStream.FlushFinalBlock();
var decryptBytes = memoryStream.ToArray();
return decryptBytes;
}
}
}
您好,我需要幫助將上述 c# 代碼轉換為等效的 python 代碼。 由於我是 python 的新手,因此不確定此處要使用哪些相關庫。 如果有人可以在這里幫助我,那就太好了。
到目前為止,我已經嘗試了下面的代碼,但看起來它不起作用:
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from PIL import Image
_encryptionKey='secret'.encode("utf-32")
salt = '\0x65\0x76\0x61\0x6e\0x20\0x4d\0x65\0x64\0x76\0x65\0x64\0x65\0x65'.encode("utf-32")
key_bytes = PBKDF2(_encryptionKey, salt, dkLen=64)
session_key=key_bytes[:32]
iv= key_bytes[:16]
cipher = AES.new(session_key, AES.MODE_CBC, iv)
val = cipher.decrypt(ency_img)
Image.open(BytesIO(val))
這里ency_img
是來自 MySQL 數據庫的加密圖像字節 object,列類型為longblob
來自 PIL Image 的錯誤
PIL.UnidentifiedImageError:無法識別圖像文件 <_io.BytesIO object at 0x7fb10d79a270>
我在@Topaco 的評論的幫助下找到了這個問題的解決方案。 謝謝你,伙計。
正如@Topaco 的評論中提到的,我必須進行以下更改:
\0x
替換為\x
_encryptionKey
和salt
的編碼更改為utf-8
而不是utf-32
iv
的值為key_bytes[32:32+16]
而不是key_bytes[:16]
以下是我的工作代碼:
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from PIL import Image
_encryptionKey='secret'.encode("utf-8")
salt = '\x65\x76\x61\x6e\x20\x4d\x65\x64\x76\x65\x64\x65\x65'.encode("utf-8")
key_bytes = PBKDF2(_encryptionKey, salt, dkLen=64)
session_key=key_bytes[:32]
iv= key_bytes[32:32+16]
cipher = AES.new(session_key, AES.MODE_CBC, iv)
img = Image.open(BytesIO(val))
print(img.size)
Image.open(BytesIO(val))
希望這會幫助別人
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.