daveslab
daveslab

Reputation: 10310

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?

Upvotes: 0

Views: 2233

Answers (2)

daveslab
daveslab

Reputation: 10310

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!

Upvotes: 2

mnistic
mnistic

Reputation: 11020

With the Cryptography module, which you can install with:

$ pip install cryptography

Assuming you have the private key stored in a file called "path/to/key.pem", first you load the private key:

from cryptography.hazmat.primitives import serialization 
with open("path/to/key.pem", "rb") as key_file: 
    private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
        backend=default_backend() 
    )

And then you decrypt with:

plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None
    )
)

Upvotes: 1

Related Questions