from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from binascii import unhexlify

# The public modulus, in hex format, as printed by globalplatform
kPub_hex = "B2A4DD33D67BFCFB7B405E55C9B6F5A578AB240794B725975FFB1600C47C2A02EE6D4E2A3F750970377EB0458663A6872E862357E773ED3A78621790153419EC0E9F6BAAE2AD898A28CD61FF0AFA82B48CD41FF3063502871255AB2E12AEF64FDEB195603C77E64951FE867E8D57004D141CC507DE4B55DA921B9F879CFFFF9D2CBC8D85D3C6E28BAC0F0A4FA62530B89C344D448F3760F9A0DD9F469098E63EA92C5328AE78D30035E704732368FBDB717499AC45513A6367C087266B05218F3636A9DD4924E8903D1F13467236E8C7D55439FB73B6EDA513CEB20FFB4E1BB69F34F20E55328C1A74B863BDD285D9B14C3B288D8CFE9B5C87308E8BB85FC923"
# The signaure, in hex format, as printed by globalplatform
signature_hex = "426C8192CAB65FAB2828C757CA3C74CC80AE761E35103735FC8CB80CD39EFA7CD61B9F494A0AC3D30DA8F3D3E086424D9970211F2241DFA40A8184CC997C1E5A6D19755A19851716F84D93794B0E7F646F8F368FBDF534762DD05119909C0BDAD7CE885CF7F848F7F130A0BEED5C188EF893D05379B979F81F9DBD4CEF6A3F22F6BE4090C0F1E7CB0118FE2DFBF7DFA19F250BC62856FC79952FC2CD60B6C5C7EF5C49CF6A091EB2CB9BD0C223B3F87C71215FAA439193780AF5ECC3242F60F2D4CA19BA0B4CE0558CAF749E569479A3D05EA4DC2F1D259DD25C3B20435DD704FE6EE1C73EDA9F627002C5B00BFCBF17911DBA93DF6FA8FFD9317E683D297D0D"
# decode the public key modulus
kPub = unhexlify(kPub_hex)
# the hex public exponent, which should be large, probably 65537. If it's 3, your card is generating weak and vulnerable signatures
kPub_exp_hex = "010001"
# decode the exponent
kPub_exp = unhexlify(kPub_exp_hex)
# decode the signature
signature = unhexlify(signature_hex)

# construct a public key
kPub_int = int.from_bytes(kPub, byteorder='big')
kPub_exp_int = int.from_bytes(kPub_exp, byteorder='big')
key = RSA.construct((kPub_int, kPub_exp_int))
# build a verifier with the public key
verifier = PKCS1_v1_5.new(key)
# set up the message to verify (raw byte form)
msg = b"\x01\x02\x03\x04\x05"
# create a digest of it
h = SHA256.new(msg)
# validate the signature against the digest
if verifier.verify(h, signature):
    print("Verified OK")
else:
    print("Verification failed")
