Search code examples
pythonauthenticationrsapublic-keypycryptodome

How to decrypt with public key in pyCryptodome (Python 3.7)


I know this question has been asked countless times but either the others that asked it were not clear enough or this is simply impossible (nobody said that though), anyway nobody ever gave a clear answer (maybe with the code). So: I am trying to build a cryptocurrency but it's purely for fun so I don't need it to be super-safe and I would have liked to use RSA to verify a user's authenticity, I encrypt the transaction message with the private key and then I send the message along with the encrypted version and then when I need to verify I ask for the public key and decrypt. Now here comes the problem: apparently it needs the private key to decrypt (which I obviously can't have) while mathematically this would work perfectly without it. Is there any way around this? Something that works similarly but isn't RSA would be fine too.


Solution

  • I found a way with a method as efficient and more secure, here is the code (took directly from the PKCS1_v1_5 documentation): The following example shows how a private RSA key (loaded from a file) can be used to compute the signature of a message:

    >>> from Crypto.Signature import pkcs1_15
    >>> from Crypto.Hash import SHA256
    >>> from Crypto.PublicKey import RSA
    >>>
    >>> message = 'To be signed'
    >>> key = RSA.import_key(open('private_key.der').read())
    >>> h = SHA256.new(message)
    >>> signature = pkcs1_15.new(key).sign(h)
    

    At the other end, the receiver can verify the signature (and therefore the authenticity of the message) using the matching public RSA key:

    >>> key = RSA.import_key(open('public_key.der').read())
    >>> h = SHA.new(message)
    >>> try:
    >>>     pkcs1_15.new(key).verify(h, signature)
    >>>     print "The signature is valid."
    >>> except (ValueError, TypeError):
    >>>    print "The signature is not valid."
    

    Hopefully this will be helpful if not here is the link for the page itself: https://pycryptodome.readthedocs.io/en/latest/src/signature/pkcs1_v1_5.html