python - AES 在 python 中加密 在 php 中解密

标签 python php encryption cryptography aes

我问这个是因为我并不真正了解 php,但必须以某种方式进行管理。 我在 python 中加密了数据,需要在 php ( serversite ) 中解密。 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() 函数存在一些问题。谁能帮我解决这个问题...

最佳答案

您正在分配额外的 4 个字符 <br>到你的 $this->iv。这将修复它:

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==

enter image description here

其中,在 rtrim($ok, '='); 之后, 会给你

rtVabOaDdf528T63xOhhww

关于python - AES 在 python 中加密 在 php 中解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63740431/

相关文章:

php - session 变量无法识别

python - 如何访问相互嵌套的多层字典和列表并将它们收集到一个列表中

python - 如何捕获python异常并将回溯文本保存为字符串

php - 逻辑或 (||) 出现无法解释的语法错误

php - 在Ubuntu 16.04上无法访问http://ip/phpmyadmin

c - if 语句计算流密码 Leviathan 源代码中的整数

php - PDO 登录脚本返回 false

ios - 当我在 IOS 中集成 CCAvenue Payment Gate way 时,我收到 Exe_Bad_Access(code=1 address=0X38)

Python 代码卡在 Iterating 中,尽管它找到了解决方案

Python:如何将 123 舍入为 100 而不是 100.0?