def encrypt_pk(pub_key, plaintext):
"""
Encrypt plaintext with the RSA public key pub_key, using CryptoHash()
as the OAEP/MGF1 padding hash.
plaintext is limited to the size of the RSA key, minus the padding, or a
few hundred bytes.
Returns a b64encoded ciphertext string.
Encryption failures result in an exception being raised.
"""
try:
ciphertext = pub_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=CryptoHash()),
algorithm=CryptoHash(),
label=None
)
)
except UnsupportedAlgorithm as e:
# a failure to encrypt our own data is a fatal error
# the most likely cause of this error is an old cryptography library
# although some newer binary cryptography libraries are linked with
# old OpenSSL versions, to fix, check 'openssl version' >= 1.0.2, then:
# pip install -I --no-binary cryptography cryptography
logging.error("Fatal error: encryption hash {} unsupported, try upgrading to cryptography >= 1.4 compiled with OpenSSL >= 1.0.2. Exception: {}".format(
CryptoHash, e))
# re-raise the exception for the caller to handle
raise e
return b64encode(ciphertext)
评论列表
文章目录