首页 > 解决方案 > 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() 函数存在一些问题。有人可以帮我解决这个问题吗...

标签: pythonphpencryptioncryptographyaes

解决方案


您正在<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

推荐阅读