Search code examples
pythonrsapublic-key-encryptionpycrypto

decrypt a message with RSA public key with PyCrypto


I want to decrypt a message with RSA public key with PyCrypto I am useing code below but getting no private key error what should changed in code below?

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64
licence_key="bla bla"
licence_key_in_bytes=licence_key.encode("utf-8")
encrypted=base64.b16decode(licence_key_in_bytes)
key = open("public_key", "r").read() 
rsakey = RSA.importKey(key)
rsakey = PKCS1_OAEP.new(rsakey)
decrypted_message= rsakey.decrypt(encrypted)

Solution

  • Encryption (providing confidentiality)

    • If you want to encrypt/decrypt in the same application, then you simple should swap the public key and the private key.
    • Encryption is always performed by the public key, decryption by the private key.
    • RSA does not have any security if you do it the other way around.
    • If you know the private key then a public key with a small public exponent can be easily guessed by an attacker.

    Signature generation (providing authenticity & integrity)

    • From the code however it seems you want to sign a message, but you are using an algorithm (RSA OAEP) that has been designed explicitly for encryption.
    • Unfortunately both concepts are not compatible. First of all, OAEP padding mechanism is not compatible with the one for signing.

    Furthermore, there may be differences in handling the keys

    • the library will handle private keys operations differently from public key operations. - - Private keys require security, such as protection against side channel attacks.
    • Note that that a public key allows for a larger range of values than a private key (the public exponent may be small or large, the private exponent should always be near the key size).

    So the components of a private key will always match those of a public key. But as public keys normally have a small public exponent, public keys may not always be accepted as private keys.

    • The only good solution is to replace your own signing operation with the correct one. - -- Fortunately Python handles PSS signing operations, take a look at the documentation here, which helpfully contains sample code.