【发布时间】:2013-12-05 03:46:46
【问题描述】:
我正在尝试将此 C# 代码转换为 Python(2.5,GAE)。问题是每次运行加密(在同一字符串上)时,python脚本中的加密字符串都是不同的。
string Encrypt(string textToEncrypt, string passphrase)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = Encoding.UTF8.GetBytes(passphrase);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = new byte[16];
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
Python 代码:(PKCS7Encoder:http://japrogbits.blogspot.com/2011/02/using-encrypted-data-between-python-and.html)
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
#declared outside of all functions
key = '####'
mode = AES.MODE_CBC
iv = '\x00' * 16
encryptor = AES.new(key, mode, iv)
encoder = PKCS7Encoder()
def function(self):
text = self.request.get('passwordTextBox')
pad_text = encoder.encode(text)
cipher = encryptor.encrypt(pad_text)
enc_cipher = base64.b64encode(cipher)
C# 代码是继承的。 Python 代码必须以相同的方式进行加密和解密,以便 C# 代码可以正确解码该值。
注意:我是 python 的菜鸟 :)
编辑:对不起。应该区分有一个函数被调用。
谢谢!
【问题讨论】:
-
您知道 IV / CBC 模式的工作原理吗?如果您每次都运行该存根,它应该为相同的输入产生相同的输出。但是,如果您使用相同的输入多次调用 encryptor.encrypt 而不重新初始化加密器(将其重置为相同的初始状态),则每次都会产生不同的输出。
-
我的编辑会改变你的评论吗?如果没有,最好的解决方法是什么?
-
通过将 encryptor = AES.new(key, mode, iv) 移动到函数中来修复。谢谢@Foon
标签: c# python encryption cryptography aes