Created
August 28, 2020 12:25
-
-
Save viewplatgh/cb690159e8ee028cb4c9483cb127e6c3 to your computer and use it in GitHub Desktop.
Use rsa sha256 public key to verify signed text in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# packages required but not limited to: | |
# asn1crypto==0.24.0 | |
# cryptography==2.2.2 | |
# pyOpenSSL==17.5.0 | |
import crypto | |
# Use the public key file: 'pub_key_filename' to verify | |
# if 'signed' is a valid one from 'plain_text' | |
# if it's valid return True, otherwise return False | |
def verify_signed_text(pub_key_filename, plain_text, signed): | |
rsa_public_key = None | |
with open(pub_key_filename, 'r') as pub_key_file: | |
rsa_public_key = pub_key_file.read() | |
pkey = crypto.load_publickey(crypto.FILETYPE_PEM, rsa_public_key) | |
x509 = crypto.X509() | |
x509.set_pubkey(pkey) | |
signed = base64.b64decode(signed) # Skip this if signed text is not encoded | |
try: | |
crypto.verify(x509, signed, | |
plain_text.encode('utf-8'), 'sha256') | |
return True | |
except crypto.Error as err: | |
return False | |
except BaseException as exp: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment