python - AES在python中加密在php中解密
问题描述
我问这个是因为我真的不知道 php 但必须以某种方式管理。我在 python 中加密了数据,需要在 php(服务器站点)中解密。 蟒蛇加密:
import hashlib
from base64 import b64encode, b64decode, urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
text = "secret"
secret_key = 'This is my secret key'
secret_iv = 'This is my secret iv'
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'=')
这给出了 'rtVabOaDdf528T63xOhhww' 输出,它是正确的 AES 加密的。
和以其他方式加密和解密的php :
<?php
$string="secret";
class CryptService{
private static $encryptMethod = 'AES-256-CBC';
private $key;
private $iv;
public function __construct(){
echo '<br>: '.$this->key = substr(hash('sha256', 'This is my secret key'), 0, 32);
echo '<br>: '.$this->iv = substr(hash('sha256', 'This is my secret iv'), 0, 16).'<br>';
}
public function decrypt($string){
// $string = strtr($data, '-_', '+/');
$string = base64_decode($string);
return openssl_decrypt($string, self::$encryptMethod, $this->key, 0, $this->iv);
}
public function encrypt($string){
$output = openssl_encrypt($string, self::$encryptMethod, $this->key, 0, $this->iv);
$output = base64_encode($output);
return $output;
}
}
$a = new CryptService;
echo $ok=$a->encrypt('secret');
echo "\n";
echo 'TEST: '.$a->decrypt($string);
echo 'BACK ok: '.$a->decrypt($ok);
echo "\n\n";
由于“iv”,openssl_decrypt() 函数存在一些问题。有人可以帮我解决这个问题吗...
解决方案
您正在<br>
为 $this->iv 分配额外的 4 个字符。这将解决它:
echo '<br>: ' . ($this->iv = substr(hash('sha256', 'This is my secret iv'), 0, 16)) . '<br>';
基本上,您. '<br>'
将 连接<br>
到您的substr()
. 我()
在变量值分配周围添加了。现在它可以工作了
cnRWYWJPYURkZjUyOFQ2M3hPaGh3dz09 TEST: BACK ok: secret
我不是加密专家,但是...我认为您的代码中有些东西不完全属于那里。当我删除这两行时:
$string = base64_decode($string);
$output = base64_encode($output);
我得到这个输出:
rtVabOaDdf528T63xOhhww==
哪个,在 a 之后rtrim($ok, '=');
,会给你
rtVabOaDdf528T63xOhhww
推荐阅读
- java - 接收实体更新时,如何在不应理解传入 DTO 的类中访问以前的值?
- excel - 如何在VB Excel中从另一个模块调用一个模块的变量
- php - 在 Laravel 5.1 中使用 wp 之类的简码渲染数据
- javascript - 如何在角度 5 的剑道 UI 树视图中添加自定义图标?
- php - 如何用我的案例重写 URL
- mysql - 查询以避免左外连接或内连接
- javascript - 如何避免角度应用程序中遵循的一系列输入?
- c# - 开始和结束音频
- javascript - 如何在网页中以单一形式和单一控制器实现两个角度js材料的md-autocomplete?
- c++ - 如何在 C++ 中将 gregorian_date 存储为 unordered_map 的键?