PYTHON openssl_public_decrypt

is this article helpful?
Python replacement for PHP's openssl_public_decrypt [ edit | history ]
from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key

def openssl_public_decrypt(key, data):
"""Decrypt data with RSA public key.

This is a rewrite of the function from PHP, using cryptography
FFI bindings to the OpenSSL library. Private key encryption is
non-standard operation and Python packages either don't offer
it at all, or it's incompatible with the PHP version.
The backend argument MUST be the OpenSSL cryptography backend.
length = backend._lib.EVP_PKEY_size(key._evp_pkey)
buffer ='unsigned char', length)
result = backend._lib.RSA_public_decrypt(
len(data), data, buffer,

# backend.openssl_assert(result == length)
return backend._ffi.buffer(buffer)

pubkey = load_pem_public_key(open('public_key.pem').read(), None, backend)
text = openssl_public_encrypt(pubkey, data);

PHP openssl_public_decrypt

PHP original manual for openssl_public_decrypt [ show | ]


(PHP 4 >= 4.0.6, PHP 5)

openssl_public_decryptDecrypts data with public key


bool openssl_public_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding= OPENSSL_PKCS1_PADDING ] )

openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted .

You can use this function e.g. to check if the message was written by the owner of the private key.





key must be the public key corresponding that was used to encrypt the data.


padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also