python - 为什么在 python 中解密时,解密在 php 中生成的字符串会部分起作用?
问题描述
我正在开发小型应用程序,但在 python 中解密数据时遇到问题。
首先,我使用以下代码在 php 中使用 AES-256-CBC 加密字符串:
function EncryptAES($data){
global $KEY;
$ivlen = openssl_cipher_iv_length("aes-256-cbc");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, NULL, $iv);
return $ciphertext;
}
现在 openssl_encrypt 返回 base64 字符串(因为我使用NULL作为第四个变量)
之后我尝试在 python 中解密它,但它只返回字符串的最后一部分。
这是python代码:
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class AESCipher:
def __init__( self, key ):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
def Decrypt(data):
cipher = AESCipher(KEY)
decrypted = cipher.decrypt(data).decode('UTF-8')
return decrypted
当然KEY变量与服务器上的相同。
现在,在使用加密数据运行Decrypt()函数后,它只返回解密字符串的一部分。
解决方案
好的,问题解决了!对于任何想知道的人,您需要在 php.ini 中预先附加 IV。默认的 openssl_encrypt 不添加它。
这是代码:
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, OPENSSL_RAW_DATA, $iv);
$DATA = base64_encode($iv.$ciphertext);
推荐阅读
- python-3.7 - 如何在python中重复输入?
- excel - 将 Excel 幂查询表列转换为字符串
- php - 在我的沙盒帐户的仪表板中显示订单的流程是什么?
- php - 如何获得我的广告组预算可以获得的点击次数和展示次数?
- c# - 一些特定条件的正则表达式
- typescript - 为什么我不能从 Typescript 中的方法动态设置样式
- python - Scikit-learn:RuntimeError:scikit-learn 估计器应始终在其 __init__ 的签名中指定其参数
- typescript - Typescript“+”运算符如何与泛型和函数一起使用?
- android - AndroidX没有找到类“android.support.v4.content.ContextCompat
- asp.net - 身份框架使用主体