PYTHON openssl_private_encrypt

is this article helpful?
Python replacement for PHP's openssl_private_encrypt [ edit | history ]
# FROM: [url][/url]

from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key

def openssl_private_encrypt(key, data):
    """Encrypt data with RSA private 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_private_encrypt(
        len(data), data, buffer,
    backend.openssl_assert(result == length)
    return backend._ffi.buffer(buffer)[:]

privkey = load_pem_private_key(open('private_key.pem').read(), None, backend)
cipher = openssl_private_encrypt(privkey, '123456');

Not just the same as the PHP version, but helpful.

PHP openssl_private_encrypt

PHP original manual for openssl_private_encrypt [ show | ]


(PHP 4 >= 4.0.6, PHP 5)

openssl_private_encryptEncrypts data with private key


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

openssl_private_encrypt() encrypts data with private key and stores the result into crypted . Encrypted data can be decrypted via openssl_public_decrypt().

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.






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