首页 > 解决方案 > 相当于 Python 中的一段 PHP 代码

问题描述

我需要在 Python 中实现一个支付端口。在这里,我必须加密一个字符串并将其发送到服务器并获得响应。我在 PHP 中有相当于这段代码的代码。但我想要 Python 中的这个函数。我提到了我的努力。我还设置了键的值。我还显示了传入的错误。感谢您的建议。以下是 PHP 代码:

function encrypt_pkcs7 ($str, $key)
{
$key = base64_decode($key);
$cipherText = OpenSSL_encrypt($str, "DES-EDE3", $key, 
OPENSSL_RAW_DATA);
return base64_encode($cipherText);
}

我对 Python 的尝试。

import base64
from Crypto.Cipher import DES3
def encrypt_DES3(terminal_id,order_id,amount):
    """

    :param terminal_id: String-for example: EUDuTQrp
    :param order_id: integer- for example: 123456
    :param amount: integer - for example: 60000
    :return: encrypt "terminal_id;oreder_id;integer"
    """
    key =base64.b64decode("YTAzZTYyNDNiMTljMzg0YzYxY2NhMGU4NjU1ODc2N2FkYTAwMGJiOQ==")
    text = terminal_id + ';' + str(order_id) + ';' + str(amount)
    def pad(text):
        while len(text) % 8 != 0:
            text += '='
        return text

    plain_text = pad(plain_text)
    cipher = DES3.new(key, DES3.MODE_ECB)
    my_export = cipher.encrypt(plain_text)

    return my_export

我得到的错误:

File "<pyshell#18>", line 1, in <module>
encrypt_DES3('EUDuTQrp',123456,60000)
File "<pyshell#17>", line 17, in encrypt_DES3
cipher = DES3.new(key, DES3.MODE_ECB)
File "/usr/lib/python3/dist-packages/Crypto/Cipher/DES3.py", line 
113, in new
return DES3Cipher(key, *args, **kwargs)
File "/usr/lib/python3/dist-packages/Crypto/Cipher/DES3.py", line 
76, in __init__
blockalgo.BlockAlgo.__init__(self, _DES3, key, *args, **kwargs)
File "/usr/lib/python3/dist-packages/Crypto/Cipher/blockalgo.py", 
line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: Invalid key size (must be either 16 or 24 bytes long)

标签: pythonpython-3.xbase64

解决方案


尝试这个

import base64
from Crypto.Cipher import DES3

def pad(text,pad_size=16):
    text_length = len(text)
    last_block_size = text_length % pad_size
    remaining_space = pad_size - last_block_size

    text = text + '='*remaining_space

    return text

def encrypt_DES3(terminal_id,order_id,amount):
    """

    :param terminal_id: String-for example: EUDuTQrp
    :param order_id: integer- for example: 123456
    :param amount: integer - for example: 60000
    :return: encrypt "terminal_id;oreder_id;integer"
    """
    secret_key_text = "YTAzZTYyND122331"   ## you can only have key of size 16 or 24
    text = terminal_id + ';' + str(order_id) + ';' + str(amount)
    text = pad(text,8)
    cipher = DES3.new(secret_key_text, DES3.MODE_ECB)
    my_export = cipher.encrypt(text)

    return my_export

推荐阅读