Search code examples
pythonpython-3.xencryptionpyopenssl

How to decrypt RSA encrypted file (via PHP and OpenSSL) with pyopenssl?


Simple n00b question: I am trying to replicate the behavior of the openssl_private_decrypt function in PHP to decrypt a file that a vendor is sending me which was encrypted via the openssl_public_encrypt function. I am using python 3.4 and thus the only library I can see available is pyopenssl, but it's sufficiently low-level that I cannot easily find out how to do what I want to do. It's probably very simple, but does anyone have an exemple of what I want to do?


Solution

  • Thanks to @mnistic it got to work, with a couple of modifications though. Here is the final working code (you have to keep in mind the defaults of openssl_private_decrypt):

    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import padding
    
    # It's critical that the file be opened in mode "rb"!
    with open("private.key", 'rb') as key_file:
      private_key = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend())
    
    with open('encrypted_file', 'rb') as encrypted_file:
      ciphertext = encrypted_file.read()
    
    plaintext = private_key.decrypt(ciphertext, padding.PKCS1v15())
    

    Please note that ciphertext needs to be shorter than the maximum chunk size of the key (which is the number of bits in the key divided by 8 for RSA). Hope that helps future Googlers!