用python加密数据,用php解密失败



我尝试在Python中加密我的数据并在PHP中解密它,但是当我使用一些数据时,我可以解密它,但是当我切换到一些更长的数据时,PHP无法解密它。我该怎么办?

import hashlib
from base64 import b64encode, b64decode, urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
text = 'randdata-sadkvp121kasap2l3'
secret_key = 'This is my secret lll'
secret_iv = 'This is my secret ada'
key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
_pad = lambda s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
txt = _pad(text)
cipher = AES.new(key, AES.MODE_CBC, iv)
output = urlsafe_b64encode(cipher.encrypt(str.encode(txt))).rstrip(b'=')
print(output) #3H-137tsFowOfREf2zekkDuL1G7gdqvRzj9BHHUCRoU
<?php
$string = '3H-137tsFowOfREf2zekkDuL1G7gdqvRzj9BHHUCRoU';
$string = base64_decode($string);
$key = substr(hash('sha256', 'This is my secret lll'), 0, 32);
$iv = substr(hash('sha256', 'This is my secret ada'), 0, 16);
var_dump(openssl_decrypt($string, 'AES-256-CBC', $key, 0, $iv));//false
<?php
$padWith = '~';
$secret = '3H-137tsFowOfREf2zekkDuL1G7gdqvRzj9BHHUCRoU';
$fixedSecret = str_replace(array('-', '_'), array('+', '/'), $secret);
$key = substr(hash('sha256', 'This is my secret lll'), 0, 32);
$iv = substr(hash('sha256', 'This is my secret ada'), 0, 16);
$decryptedSecret = openssl_decrypt($fixedSecret, 'AES-256-CBC', $key, OPENSSL_ZERO_PADDING, $iv);
//$decrypted_secret = openssl_decrypt($decoded_secret, $method, $hashKey, OPENSSL_RAW_DATA+OPENSSL_ZERO_PADDING, $iv_hash);
var_dump(rtrim($decryptedSecret, $padWith));//randdata-sadkvp121kasap2l3

相关内容

  • 没有找到相关文章

最新更新