I need to sign and verify a message using RSA public and private key. The if verifier.verify(h, signature) portion at receiver, every time returns the "Signature not authentic" error. Even though everything is correct. What am I doing wrong? What is the most likely cause for this problem?
I have generated keys using the following code
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
key = RSA.generate(1024)
private_key=key.exportKey()
public_key=key.publickey().exportKey()
At sender,
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
private_key="""Private key here
-----END RSA PRIVATE KEY-----"""
message = 'To be signed'
priv_key = RSA.importKey(private_key)
h = SHA256.new(message)
signature = PKCS1_v1_5.new(priv_key).sign(h)
f=open('sign.txt','w')
f.write(signature)
At receiver,
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from base64 import b64decode
public_key="""public key here"""
pub_key = RSA.importKey(public_key)
message = 'To be signed'
f=open('sign.txt')
sig=f.readlines()
signature=sig[0]
h = SHA256.new(message)
verifier = PKCS1_v1_5.new(pub_key)
if verifier.verify(h, signature):
print "The signature is authentic."
else:
print "The signature is not authentic."
I am new to python. Any help will be appreciated. Thanks
On the sender, you get the signature and save it as binary into a file
On the receiver, you read the signature from the file as it is text, then take the first line.
just replace this:
sig=f.readlines()
signature=sig[0]
by
signature=f.read()
If you want to stick with the "text" mode, you need to encode the signature in base64 and write it to the file, and in receiver side, read the first line, and decode the base64. To do that :
On sender, you can set :
f.write(signature.encode('base64').replace('\n', ''))
and on receiver:
sig=f.readlines()
signature=sig[0].decode("base64")