我只是想知道是否有可能将PHP加密函数转换为Python?我使用PHP函数加密USER ID并将其存储在Database中,现在我需要在Python中解密USER ID,我使用的是PHP函数:
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 );
}发布于 2017-05-06 08:47:36
下面是您的函数“转换”为python
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一个新的建议
openssl_decrypt,不推荐mcrypt_decryptNote
这将不适用于MCRYPT_RIJNDAEL_256,因为它使用32个字节块。
但你可以用MCRYPT_RIJNDAEL_128或openssl
下面是PHP中openssl AES CBC的一个示例:
function encrypt($data, $key) {
$method = "aes-" . strlen($key) * 8 . "-cbc";
$iv = openssl_random_pseudo_bytes(16);
$encoded = base64_encode($iv . openssl_encrypt($data, $method, $key, TRUE, $iv));
return $encoded;
}
function decrypt($data, $key) {
$method = "aes-" . strlen($key) * 8 . "-cbc";
$iv = substr(base64_decode($data), 0, 16);
$decoded = openssl_decrypt(substr(base64_decode($data), 16), $method, $key, TRUE, $iv);
return $decoded;
}Python代码:
from Crypto.Cipher import AES
from Crypto import Random
import base64
def encrypt(data, key):
pkcs7pad = lambda data: data + chr(16-(len(data)%16)).encode() * (16-(len(data)%16))
iv = Random.new().read(16)
cipher = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
encoded = base64.b64encode(iv + cipher.encrypt(pkcs7pad(data)))
return encoded
def decrypt(data, key):
pkcs7unpad = lambda data: data[:-ord(data[-1:])]
cipher = AES.new(key=key, mode=AES.MODE_CBC, IV=base64.b64decode(data)[:16])
decoded = cipher.decrypt(base64.b64decode(data)[16:])
return pkcs7unpad(decoded)使用上面的函数,您可以在python中使用PHP解密进行加密,反之亦然。
假设键具有有效大小(16、24或32字节)
https://stackoverflow.com/questions/43818119
复制相似问题