【发布时间】:2020-12-23 16:23:26
【问题描述】:
我问这个是因为我并不真正了解 php,但必须以某种方式管理。 我在 python 中加密了数据,需要在 php(服务器站点)中解密。 python 加密:
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() 函数存在一些问题。谁能帮我解决这个问题...
【问题讨论】:
-
使用您当前的代码,您应该会收到关于 IV 太长的警告(传递的是 20 个字节,例外的是 16 个字节)。如果您没有收到此错误消息,请尝试通过将
error_reporting(-1);放在脚本的第一行来启用它 -
感谢 EdvinasPocius,Martin Toms 已经帮我解决了这个问题,但还有另一个问题.. 我无法解密我在 python 中加密的内容,基本上
标签: python php encryption cryptography aes