PHP在Python中打开SSL AES

我正在使用PHP用于解密AES-256-CBC消息的项目

<?php

class CryptService{
    private static $encryptMethod = 'AES-256-CBC';
    private $key;
    private $iv;

    public function __construct(){
        $this->key = hash('sha256', 'c7b35827805788e77e41c50df44441491098be42');
        $this->iv = substr(hash('sha256', 'c09f6a9e157d253d0b2f0bcd81d338298950f246'), 0, 16);
    }

    public function decrypt($string){
        $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 $a->encrypt('secret');
echo "\n";
echo $a->decrypt('S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09');
echo "\n";

产量

>>> S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09
>>> secret

现在,我必须编写用于加密数据的Python 3代码.
我尝试使用PyCrypto,但没有成功.我的代码:

import base64
import hashlib
from Crypto.Cipher import AES

class AESCipher:
    def __init__(self, key, iv):
        self.key = hashlib.sha256(key.encode('utf-8')).digest()
        self.iv = hashlib.sha256(iv.encode('utf-8')).digest()[:16]

    __pad = lambda self,s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
    __unpad = lambda self,s: s[0:-ord(s[-1])]

    def encrypt( self, raw ):
        raw = self.__pad(raw)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return base64.b64encode(cipher.encrypt(raw))

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
        return self.__unpad(cipher.decrypt(enc).decode("utf-8"))

cipher = AESCipher('c7b35827805788e77e41c50df44441491098be42', 'c09f6a9e157d253d0b2f0bcd81d338298950f246')

enc_str = cipher.encrypt("secret")
print(enc_str)

输出

>>> b'tnF87LsVAkzkvs+gwpCRMg=='

但是我需要输出S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09,它将PHP解密为秘密.如何修改Python代码以获得预期的输出?

解决方法:

默认情况下,PHP’s hash输出一个十六进制编码的字符串,但是Python的.digest()返回字节.您可能想使用.hexdigest():

def __init__(self, key, iv):
    self.key = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
    self.iv = hashlib.sha256(iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")

初始化向量(IV)的思想是为使用相同密钥的加密提供随机性.如果您使用相同的IV,则攻击者可能会推断出您两次发送相同的消息.这可以被视为损坏的协议.

IV不应被认为是秘密的,因此您只需将其与密文一起发送即可.通常在加密期间将其添加到密文中,然后在解密之前将其切开.

上一篇:Java DES加密/解密方法


下一篇:BouncyCastle C#公钥与GnuPG不同