Skip to content

Instantly share code, notes, and snippets.

@AlecDusheck
Created May 9, 2023 02:16
Show Gist options
  • Save AlecDusheck/c352fd080a32f071a97c3a54c8533356 to your computer and use it in GitHub Desktop.
Save AlecDusheck/c352fd080a32f071a97c3a54c8533356 to your computer and use it in GitHub Desktop.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Hash import SHA256
from base64 import b64encode, b64decode
import hashlib
import os
# Replace with the path to your RSA public key file
public_key_file_path = 'rsa_public_key.key'
def load_public_key(file_path):
with open(file_path, 'rb') as file:
key_data = file.read()
public_key = RSA.import_key(key_data)
return public_key
def rsa_encrypt_by_public_key(data, public_key):
cipher = PKCS1_v1_5.new(public_key)
encrypted_data = cipher.encrypt(data)
return encrypted_data
def sha256_string(data):
sha256 = hashlib.sha256()
sha256.update(data.encode('utf-8'))
return sha256.digest()
PUBLIC_KEY = load_public_key(public_key_file_path)
input_dict = {
'appId': 1,
}
def obtain_sign(input_dict):
sorted_items = sorted(input_dict.items())
data = '&'.join(f'{k}={v}' for k, v in sorted_items) + 'D9519A4B756946F081B7BB5B5E8D1197'
hashed_data = sha256_string(data)
encrypted_data = rsa_encrypt_by_public_key(hashed_data, PUBLIC_KEY)
return b64encode(encrypted_data).decode('utf-8')
sign_result = obtain_sign(input_dict)
print("Generated signature:", sign_result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment