我有两个程序,一个是用C#.NET开发的,具有以下C#加密/解密功能:
public static string Encrypt(string plainText, string keyString)
{
byte[] cipherData;
Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(keyString);
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
cipherData = ms.ToArray();
}
byte[] combinedData = new byte[aes.IV.Length + cipherData.Length];
Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length);
Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length);
return Convert.ToBase64String(combinedData);
}
public static string Decrypt(string combinedString, string keyString)
{
string plainText;
byte[] combinedData = Convert.FromBase64String(combinedString);
Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(keyString);
byte[] iv = new byte[aes.BlockSize / 8];
byte[] cipherText = new byte[combinedData.Length - iv.Length];
Array.Copy(combinedData, iv, iv.Length);
Array.Copy(combinedData, iv.Length, cipherText, 0, cipherText.Length);
aes.IV = iv;
aes.Mode = CipherMode.CBC;
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
plainText = sr.ReadToEnd();
}
}
return plainText;
}
}另一个程序是使用Python的,需要解密来自C#的加密字符串程序。
Python的加密/解密函数是什么,以便Python的解密函数可以通过上面的C#加密函数解密加密的字符串,C#的解密函数也可以通过Python的加密函数解密加密的字符串?
发布于 2021-04-28 11:45:06
以下是为我工作的Python函数:
import Crypto.Random
from Crypto.Cipher import AES
import base64
from Crypto.Util.Padding import unpad, pad
def encrypt(plain_text, key_string):
raw = pad(plain_text.encode(), AES.block_size)
iv = Crypto.Random.get_random_bytes(AES.block_size)
cipher = AES.new(key_string, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(combined_string, key_string):
enc = base64.b64decode(combined_string)
iv = enc[:AES.block_size]
cipher = AES.new(key_string, AES.MODE_CBC, iv)
msg = unpad(cipher.decrypt(enc[AES.block_size:]), AES.block_size)
return msg.decode()https://stackoverflow.com/questions/67274144
复制相似问题