Skip to content

Instantly share code, notes, and snippets.

@vladmeh
Created May 17, 2023 16:24
Show Gist options
  • Save vladmeh/74051a31e3c6de2bc8dc8a75a8ed5991 to your computer and use it in GitHub Desktop.
Save vladmeh/74051a31e3c6de2bc8dc8a75a8ed5991 to your computer and use it in GitHub Desktop.

Revisions

  1. vladmeh created this gist May 17, 2023.
    83 changes: 83 additions & 0 deletions encrypt_decrypt_signature_pscb.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,83 @@
    import base64
    import hashlib
    import json
    from hashlib import sha256

    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad, unpad


    def _base64_message(message: str) -> str:
    message_bytes = message.encode('utf-8')
    base64_bytes = base64.b64encode(message_bytes)
    return base64_bytes.decode('utf-8')


    def signature(message: str, merchant_key: str) -> str:
    return sha256((message + merchant_key).encode('utf-8')).hexdigest()


    def encrypt(plaintext: str, key: bytes) -> bytes:
    data_bytes = bytes(plaintext, 'utf-8')
    padded_bytes = pad(data_bytes, AES.block_size)

    cipher_encrypt = AES.new(key, AES.MODE_ECB)

    return cipher_encrypt.encrypt(padded_bytes)


    def decrypt(ciphered_text: bytes, key: bytes) -> str:
    cipher_decrypt = AES.new(key, AES.MODE_ECB)

    raw_bytes = cipher_decrypt.decrypt(ciphered_text)
    deciphered_bytes = unpad(raw_bytes, AES.block_size)

    return deciphered_bytes.decode('utf-8')


    if __name__ == '__main__':
    message = {
    "payments": [
    {
    "orderId": "480c505a-10d7-4122-98b0-0828c0b07659",
    "showOrderId": "ЗаказX123",
    "paymentId": "12345",
    "marketPlace": "23",
    "paymentMethod": "ac",
    "state": "end",
    "stateDate": "2013-11-25T18:14:44.931+03:00",
    "amount": 1.00
    },
    {
    "orderId": "5a8130df-0e19-4ff1-b331-f57c8b6c90e6",
    "showOrderId": "ЗаказX124",
    "paymentId": "12346",
    "marketPlace": "23",
    "paymentMethod": "ac",
    "state": "end",
    "stateDate": "2013-11-25T18:14:44.931+03:00",
    "amount": 1.00
    },
    {
    "orderId": "X125",
    "showOrderId": "ЗаказX125",
    "paymentId": "12346",
    "marketPlace": "23",
    "paymentMethod": "ac",
    "state": "end",
    "stateDate": "2013-11-25T18:14:44.931+03:00",
    "amount": 1.00
    },
    ]
    }

    plain_text = json.dumps(message, ensure_ascii=False)

    merchant_key = '111111'
    key_md5 = hashlib.md5(merchant_key.encode())

    cipher_text = encrypt(plain_text, key_md5.digest())
    print(cipher_text)

    plain_text = decrypt(cipher_text, key_md5.digest())
    print(plain_text)