这里是你的函数“翻译”给蟒蛇
from Crypto.Cipher import AES
from hashlib import md5
def decrypt(id):
cryptKey = '123'
cipher = AES.new(key=md5(cryptKey).hexdigest(), mode=AES.MODE_CBC, IV=md5(md5(cryptKey).hexdigest()).hexdigest()[:16])
decoded = cipher.decrypt(id.decode('base64')).rstrip('\0')
return decoded
一个fiew建议
1.使用随机IV
2.使用更复杂的关键
3.不要硬编码的关键
4.使用openssl_decrypt
,mcrypt_decrypt
已被弃用
注意
,因为它使用32字节块这不会MCRYPT_RIJNDAEL_256
工作。
你可以使用MCRYPT_RIJNDAEL_128
或openssl
这里是PHP与OpenSSL的AES-256 CBC一个例子:
function encrypt($id) {
$cryptKey ='123';
$encoded = base64_encode(openssl_encrypt($id, "aes-256-cbc", md5($cryptKey), TRUE, substr(md5(md5($cryptKey)), 0, 16)));
return($encoded);
}
function decrypt($id) {
$cryptKey ='123';
$decoded = openssl_decrypt(base64_decode($id), "aes-256-cbc", md5($cryptKey), TRUE, substr(md5(md5($cryptKey)), 0, 16));
return($decoded);
}
Python代码:
def encrypt(id):
cryptKey='123'
pkcs7pad = lambda data : data + ''.join(chr(16-(len(data)%16)) for _ in range(16-(len(data)%16)))
cipher = AES.new(key=md5(cryptKey).hexdigest(), mode=AES.MODE_CBC, IV=md5(md5(cryptKey).hexdigest()).hexdigest()[:16])
encoded = cipher.encrypt(pkcs7pad(id)).encode('base64')
return encoded
def decrypt(id):
cryptKey='123'
pkcs7unpad = lambda data : data[:-ord(data[-1:])]
cipher = AES.new(key=md5(cryptKey).hexdigest(), mode=AES.MODE_CBC, IV=md5(md5(cryptKey).hexdigest()).hexdigest()[:16])
decoded = cipher.decrypt(id.decode('base64'))
return pkcs7unpad(decoded)
有了可以加密在上述功能PHP - 用python解密,反之亦然
[解密Python中用MC加密的字符串RYPT \ _RIJNDAEL \ _256在PHP](http://stackoverflow.com/questions/8217269/decrypting-strings-in-python-that-were-encrypted-with-mcrypt-rijndael-256-in-php) –