2017-05-06 153 views
2

我只是想知道是否有可能将PHP加密函数转换为Python?我使用PHP函数加密USER ID并将其存储在Database,现在我需要在Python解密USER ID,我用这个PHP功能:PHP函数转换为Python

function decrypt($id) { 
     $cryptKey = '123'; 
     $decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($cryptKey),   base64_decode($id), MCRYPT_MODE_CBC, md5(md5($cryptKey))), "\0"); 
     return($decoded); 
    } 
+0

[解密Python中用MC加密的字符串RYPT \ _RIJNDAEL \ _256在PHP](http://stackoverflow.com/questions/8217269/decrypting-strings-in-python-that-were-encrypted-with-mcrypt-rijndael-256-in-php) –

回答

4

这里是你的函数“翻译”给蟒蛇

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_decryptmcrypt_decrypt已被弃用

注意
,因为它使用32字节块这不会MCRYPT_RIJNDAEL_256工作。
你可以使用MCRYPT_RIJNDAEL_128openssl

这里是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解密,反之亦然

+0

谢谢,你已经救了我的一天!:) – Streem

+1

Allways乐于提供帮助。你试过了吗? –

+0

是的,我试过了我收到错误:“binascii.Error:不正确的填充”我编码的PHP ID:“VjceE1sAhxf2kUJYJX5q1BruIco2ne9SBAjzmbgjfno%3D”据我所知,某些东西与我编码的ID字符串不正确我正在寻找解决方案 – user2808421