我需要在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)
答案 0 :(得分:0)
尝试
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