【问题标题】:AES encrypt in python decrypt in phpAES在python中加密在php中解密
【发布时间】: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


【解决方案1】:

您正在为 $this->iv 分配额外的 4 个字符 &lt;br&gt;。这将解决它:

echo '<br>: ' . ($this->iv = substr(hash('sha256', 'This is my secret iv'), 0, 16)) . '<br>';

基本上,您的. '&lt;br&gt;'&lt;br&gt; 连接到您的substr()。我在变量赋值周围添加了()。现在可以了

cnRWYWJPYURkZjUyOFQ2M3hPaGh3dz09 TEST: BACK ok: secret

我不是加密专家,但是...我认为您的代码中有些东西并不完全属于那里。当我删除这两行时:

$string = base64_decode($string);
$output = base64_encode($output);

我得到这个输出:

rtVabOaDdf528T63xOhhww==

rtrim($ok, '='); 之后,会给你什么

rtVabOaDdf528T63xOhhww

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2021-09-02
    相关资源
    最近更新 更多