I'm trying to understand the pyCrypto encrypt and decrypt methods for public and private keys, and I'm seeing something strange. Suppose I have a set of private and public keys, stored in files dummy_private.txt and dummy_public.txt.
I create a private key object and public key object like this:
private_key_file='dummy_private.txt'
f = open(private_key_file, 'r')
privateKey = RSA.importKey(f.read(),None)
f.close()
public_key_file='dummy_public.txt'
f = open(public_key_file, 'r')
publicKey = RSA.importKey(f.read(),None)
f.close()
Now suppose I want to encrypt some message. I can do it like this:
s='This is a super secret message'
sutf8=s.encode('utf8')
enc=publicKey.encrypt(sutf8,None)[0]
encb64=base64.encodestring(enc)
print "Public key Encoded message is %s" % (encb64,)
This makes sense because I am encrypting with the public key and I should be able to decrypt with the private key.
However, I can also encrypt the above using the private key, and it gives me the same result!
enc2=privateKey.encrypt(sutf8,None)[0]
encb642=base64.encodestring(enc2)
print "Private key Encoded message is %s" % (encb642,)
When I print out the base64 encoded version of the encrypted data, using either the private key or the public key, they are the same! Why is that?
And this raises the problem of digitally signing something with the private key. If I can sign something with the public key and get the same results, then how does signing verify that I am who I say I am? This must be some issue with the encrypt method that I don't understand. Can someone please explain?
Since encrypting with both the public key and private key gives the same results, it appears that decrypting with the private key can be done regardless of whether the encryption was done with the private key or the public key. I'm totally confused as to why one could encrypt with the private key and get a result that is the same as if it were done with the public key.