我需要用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)
最佳答案
试试这个
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
关于python - 相当于Python中的一段PHP代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56297328/