Skip to content

Instantly share code, notes, and snippets.

@cevaris
Last active October 17, 2023 17:42
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save cevaris/e003cdeac4499d225f06 to your computer and use it in GitHub Desktop.
Save cevaris/e003cdeac4499d225f06 to your computer and use it in GitHub Desktop.
Sign and Verify using Python pycrypto
#!/usr/bin/env bash
# Generate RSA private key
openssl genrsa -out private_key.pem 1024
#!/usr/bin/env python
from base64 import (
b64encode,
b64decode,
)
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
message = "I want this stream signed"
digest = SHA256.new()
digest.update(message)
# Read shared key from file
private_key = False
with open ("private_key.pem", "r") as myfile:
private_key = RSA.importKey(myfile.read())
# Load private key and sign message
signer = PKCS1_v1_5.new(private_key)
sig = signer.sign(digest)
# Load public key and verify message
verifier = PKCS1_v1_5.new(private_key.publickey())
verified = verifier.verify(digest, sig)
assert verified, 'Signature verification failed'
print 'Successfully verified message'
@cevaris
Copy link
Author

cevaris commented Mar 2, 2015

To test

  • Invoke ./generate_key.sh from shell
  • Pip instlal requirements.txt file
  • Invoke sign_verify.py python script

@cryptid11
Copy link

If I do not have the key object but just the pubkey string and I need to rewrite this function:


def verify(message, signature, pubkey):
    hash = MD5.new(message).digest()
    return pubkey.verify(hash, signature)

how do I do this? (basically I need to create a random pubkey object and then changing in it the only usefult info that is the actual pubkey)

btw pubkey is defined as Crypto.PublicKey.RSA.generate(1024, os.urandom).publickey()

@ErpMstar
Copy link

Hi
I am using same using same Python code for getting md5 digest. And also doing similar to this in JavaScript to get md5 digest.
But getting different values for same message. I am confused, how to check which one correct and why the other one is wrong.
Any idea how to fix this?

@cevaris
Copy link
Author

cevaris commented Jun 27, 2021

Any idea how to fix this?
@ErpMstar TBH, i have no idea.

You would not need to use this script for just calculating MD5 digests.
Perhaps these links can help..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment