-2
我是新的python/django。我想使用AES加密。 搜索後,我發現這樣的一些庫:https://gist.github.com/jeetsukumaran/1291836 但我不能使用它們,因爲我有IV但這沒有IV代碼。 我有c#中的示例代碼。任何人都可以幫助我將此代碼轉換爲Python代碼?python AES加密
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace AESUtility {
public class AES {
string AES_Key = string.Empty;
string AES_IV = string.Empty;
public AES(string AES_Key, string AES_IV) {
this.AES_Key = AES_Key;
this.AES_IV = AES_IV;
}
public bool Encrypt(String Input, out string encryptedString) {
try {
var aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(this.AES_Key);
aes.IV = Convert.FromBase64String(this.AES_IV);
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] xBuff = null;
using(var ms = new MemoryStream()) {
using(var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) {
byte[] xXml = Encoding.UTF8.GetBytes(Input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
encryptedString = Convert.ToBase64String(xBuff);
return true;
} catch (Exception ex) {
encryptedString = string.Empty;
return false;
}
}
public bool Decrypt(String Input, out string decodedString) {
try {
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(this.AES_Key);
aes.IV = Convert.FromBase64String(this.AES_IV);
var decrypt = aes.CreateDecryptor();
byte[] xBuff = null;
using(var ms = new MemoryStream()) {
using(var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) {
byte[] xXml = Convert.FromBase64String(Input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
decodedString = Encoding.UTF8.GetString(xBuff);
return true;
} catch (Exception ex) {
decodedString = string.Empty;
return false;
}
}
}
}
我投票關閉這一問題作爲題外話,因爲堆棧溢出不是一個代碼編寫的服務。如果您在轉換代碼時遇到特殊問題,請更新問題。 – Alasdair
這個C#代碼只是我想要的一個樣本。我不需要有人把它轉換成python。 –
你可以使用http://pythonhosted.org/pycrypto/,它支持設置自己的IV。例如:http://pythonhosted.org/pycrypto/Crypto.Cipher.AES-module.html – valentin