在PHP(openssl)中加密字符串;然后在python3中解密

2024-09-28 01:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图加密用户输入,这是第一次验证和净化的PHP。然后使用openssl对数据进行加密,并存储在MYSQL后端。随着时间的推移,我们希望下载该表并用Python解密它。所以我在考虑一个跨语言的要求。你知道吗

我有以下字符串作为用户输入:

someone.somebody@blabla.com

使用PHP的内置方法对其进行净化:

filter_var($verifiedMail, FILTER_SANITIZE_EMAIL)

然后将其传递给PHP脚本的加密逻辑:

$lock = "82YoH8jE7TJyEX2hLzFe35wTPaaDgVP1";     // use a 256 bit key!!!!!
/*Ideally you'd define the $lock as defined constant and store it elsewhere!!!*/
$method = 'aes-256-cfb';

$ivlen = openssl_cipher_iv_length($method);
$isSecure = false;
do{
    $iv = openssl_random_pseudo_bytes($ivlen,$isSecure);
}while(!isSecure);

$mailStorage = openssl_encrypt($mail, $method, $lock, 0, $iv);

unset($method, $lock, $ivlen);

在SQL数据库中,我存储了两个变量:$iv$mailStorage 对于此迭代,这些值为:

$iv = '1abcd16944cc06c09e1d1635108a9077';
$mailStorage = 'gRDzkzHiysRqfjNXAYY+TWJ+88LtUcWfPFkn';

我的$iv变量通过在数据库中插入值时调用bin2hex($iv)存储为十六进制值。到目前为止还不错;(我想?)你知道吗

这些值在数据库中,PHP脚本不会抛出错误。所以我继续研究Python解密部分。与此相关的块是:

import binascii
from Crypto.Cipher import AES
from base64 import b64decode

securedoutput = "gRDzkzHiysRqfjNXAYY+TWJ+88LtUcWfPFkn"  #the result of the encryption done by php
vector = "1abcd16944cc06c09e1d1635108a9077"# the IV generated by PHP and stored as hex in the database
password = "82YoH8jE7TJyEX2hLzFe35wTPaaDgVP1"##the key used for encryption

iv = binascii.unhexlify(vector)
password = password.encode()
cipher = AES.new(password, AES.MODE_CFB, iv)
securedoutput = b64decode(securedoutput)
data = cipher.decrypt(securedoutput)
print(data)
print(data.decode())

我首先将十六进制初始化向量转换回二进制;然后对python模块似乎需要的密码进行编码。你知道吗

当我打印出data-变量时,我得到:

b'sBD\xec@\x90\xbe\xe3\xe6\xccdv\x13\xb8\xb06@\x1a\xe6r\x82\xdfwe\xb0\xf4\x80'

当应用data.decode()时,我得到: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xec in position 3: invalid continuation byte

我的主要问题是:为什么我的python输出现在与PHP输入匹配;在加密和/或解密字符串时我做错了什么?你知道吗

另一个与防御编程原则更相关的问题与这个PHP块有关:

$isSecure = false;
do{
    $iv = openssl_random_pseudo_bytes($ivlen,$isSecure);
}while(!isSecure);

我应该给这个while循环增加一个限制吗;或者我可以假设openssl不需要100次迭代来为$iv找到一个安全值吗?我应该对此做些什么考虑?你知道吗

最后,密码学对我来说是一个全新的领域,过去几天我一直在阅读初始化向量、加密模式等。。。据我所知,这应该是安全的,还是我大错特错了?我没有应用填充,因为我被引导相信CFB模式不需要这个。假设我的PHP脚本没有泄漏;如果数据库泄漏(因此ivencrypted output)是公开的,那么最坏的情况是什么?你知道吗

我一直在研究其他似乎使用过时模块的问题,例如:

mcrypt:Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP

他们帮助我理解了这个问题,但显然还不够。你知道吗


Tags: thein脚本数据库lockdatapasswordmethod

热门问题