8. Reference

This is the class and function reference. For more usage information see the Usage page.

8.1. Functions

rsa.encrypt(message: bytes, pub_key: rsa.key.PublicKey)

Encrypts the given message using PKCS#1 v1.5

Parameters
  • message – the message to encrypt. Must be a byte string no longer than k-11 bytes, where k is the number of bytes needed to encode the n component of the public key.

  • pub_key – the rsa.PublicKey to encrypt with.

Raises

OverflowError – when the message is too large to fit in the padded block.

>>> from rsa import key, common
>>> (pub_key, priv_key) = key.newkeys(256)
>>> message = b'hello'
>>> crypto = encrypt(message, pub_key)

The crypto text should be just as long as the public key ‘n’ component:

>>> len(crypto) == common.byte_size(pub_key.n)
True
rsa.decrypt(crypto: bytes, priv_key: rsa.key.PrivateKey) → bytes

Decrypts the given message using PKCS#1 v1.5

The decryption is considered ‘failed’ when the resulting cleartext doesn’t start with the bytes 00 02, or when the 00 byte between the padding and the message cannot be found.

Parameters
Raises

DecryptionError – when the decryption fails. No details are given as to why the code thinks the decryption fails, as this would leak information about the private key.

>>> import rsa
>>> (pub_key, priv_key) = rsa.newkeys(256)

It works with strings:

>>> crypto = encrypt(b'hello', pub_key)
>>> decrypt(crypto, priv_key)
b'hello'

And with binary data:

>>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key)
>>> decrypt(crypto, priv_key)
b'\x00\x00\x00\x00\x01'

Altering the encrypted information will likely cause a rsa.pkcs1.DecryptionError. If you want to be sure, use rsa.sign().

Warning

Never display the stack trace of a rsa.pkcs1.DecryptionError exception. It shows where in the code the exception occurred, and thus leaks information about the key. It’s only a tiny bit of information, but every bit makes cracking the keys easier.

>>> crypto = encrypt(b'hello', pub_key)
>>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte
>>> decrypt(crypto, priv_key)
Traceback (most recent call last):
...
rsa.pkcs1.DecryptionError: Decryption failed
rsa.sign(message: bytes, priv_key: rsa.key.PrivateKey, hash_method: str) → bytes

Signs the message with the private key.

Hashes the message, then signs the hash with the given key. This is known as a “detached signature”, because the message itself isn’t altered.

Parameters
  • message – the message to sign. Can be an 8-bit string or a file-like object. If message has a read() method, it is assumed to be a file-like object.

  • priv_key – the rsa.PrivateKey to sign with

  • hash_method – the hash method used on the message. Use ‘MD5’, ‘SHA-1’, ‘SHA-224’, SHA-256’, ‘SHA-384’ or ‘SHA-512’.

Returns

a message signature block.

Raises

OverflowError – if the private key is too small to contain the requested hash.

rsa.verify(message: bytes, signature: bytes, pub_key: rsa.key.PublicKey) → str

Verifies that the signature matches the message.

The hash method is detected automatically from the signature.

Parameters
  • message – the signed message. Can be an 8-bit string or a file-like object. If message has a read() method, it is assumed to be a file-like object.

  • signature – the signature block, as created with rsa.sign().

  • pub_key – the rsa.PublicKey of the person signing the message.

Raises

VerificationError – when the signature doesn’t match the message.

Returns

the name of the used hash.

rsa.find_signature_hash(signature: bytes, pub_key: rsa.key.PublicKey) → str

Returns the hash name detected from the signature.

If you also want to verify the message, use rsa.verify() instead. It also returns the name of the used hash.

Parameters
  • signature – the signature block, as created with rsa.sign().

  • pub_key – the rsa.PublicKey of the person signing the message.

Returns

the name of the used hash.

rsa.newkeys(keysize)

Generates public and private keys, and returns them as (pub, priv).

The public key is also known as the ‘encryption key’, and is a rsa.PublicKey object. The private key is also known as the ‘decryption key’ and is a rsa.PrivateKey object.

Parameters
  • nbits – the number of bits required to store n = p*q.

  • accurate – when True, n will have exactly the number of bits you asked for. However, this makes key generation much slower. When False, n` may have slightly less bits.

  • poolsize – the number of processes to use to generate the prime numbers. If set to a number > 1, a parallel algorithm will be used. This requires Python 2.6 or newer.

  • exponent (int) – the exponent for the key; only change this if you know what you’re doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537.

Returns

a tuple (rsa.PublicKey, rsa.PrivateKey)

The poolsize parameter was added in Python-RSA 3.1 and requires Python 2.6 or newer.

8.2. Classes

Note

Storing public and private keys via the pickle module is possible. However, it is insecure to load a key from an untrusted source. The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

class rsa.PublicKey(n: int, e: int)

Represents a public RSA key.

This key is also known as the ‘encryption key’. It contains the ‘n’ and ‘e’ values.

Supports attributes as well as dictionary-like access. Attribute access is faster, though.

>>> PublicKey(5, 3)
PublicKey(5, 3)
>>> key = PublicKey(5, 3)
>>> key.n
5
>>> key['n']
5
>>> key.e
3
>>> key['e']
3
blind(message: int, r: int) → int

Performs blinding on the message using random number ‘r’.

Parameters
  • message (int) – the message, as integer, to blind.

  • r (int) – the random number to blind with.

Returns

the blinded message.

Return type

int

The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29

classmethod load_pkcs1(keyfile: bytes, format='PEM') → rsa.key.AbstractKey

Loads a key in PKCS#1 DER or PEM format.

Parameters
  • keyfile (bytes) – contents of a DER- or PEM-encoded file that contains the key.

  • format (str) – the format of the file to load; ‘PEM’ or ‘DER’

Returns

the loaded key

Return type

AbstractKey

classmethod load_pkcs1_openssl_der(keyfile: bytes) → rsa.key.PublicKey

Loads a PKCS#1 DER-encoded public key file from OpenSSL.

Parameters

keyfile – contents of a DER-encoded file that contains the public key, from OpenSSL.

Returns

a PublicKey object

classmethod load_pkcs1_openssl_pem(keyfile: bytes) → rsa.key.PublicKey

Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.

These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY.

The contents of the file before the “—–BEGIN PUBLIC KEY—–” and after the “—–END PUBLIC KEY—–” lines is ignored.

Parameters

keyfile (bytes) – contents of a PEM-encoded file that contains the public key, from OpenSSL.

Returns

a PublicKey object

save_pkcs1(format='PEM') → bytes

Saves the key in PKCS#1 DER or PEM format.

Parameters

format (str) – the format to save; ‘PEM’ or ‘DER’

Returns

the DER- or PEM-encoded key.

Return type

bytes

unblind(blinded: int, r: int) → int

Performs blinding on the message using random number ‘r’.

Parameters
  • blinded – the blinded message, as integer, to unblind.

  • r – the random number to unblind with.

Returns

the original message.

The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29

class rsa.PrivateKey(n: int, e: int, d: int, p: int, q: int)

Represents a private RSA key.

This key is also known as the ‘decryption key’. It contains the ‘n’, ‘e’, ‘d’, ‘p’, ‘q’ and other values.

Supports attributes as well as dictionary-like access. Attribute access is faster, though.

>>> PrivateKey(3247, 65537, 833, 191, 17)
PrivateKey(3247, 65537, 833, 191, 17)

exp1, exp2 and coef will be calculated:

>>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
>>> pk.exp1
55063
>>> pk.exp2
10095
>>> pk.coef
50797
blind(message: int, r: int) → int

Performs blinding on the message using random number ‘r’.

Parameters
  • message (int) – the message, as integer, to blind.

  • r (int) – the random number to blind with.

Returns

the blinded message.

Return type

int

The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29

blinded_decrypt(encrypted: int) → int

Decrypts the message using blinding to prevent side-channel attacks.

Parameters

encrypted (int) – the encrypted message

Returns

the decrypted message

Return type

int

blinded_encrypt(message: int) → int

Encrypts the message using blinding to prevent side-channel attacks.

Parameters

message (int) – the message to encrypt

Returns

the encrypted message

Return type

int

classmethod load_pkcs1(keyfile: bytes, format='PEM') → rsa.key.AbstractKey

Loads a key in PKCS#1 DER or PEM format.

Parameters
  • keyfile (bytes) – contents of a DER- or PEM-encoded file that contains the key.

  • format (str) – the format of the file to load; ‘PEM’ or ‘DER’

Returns

the loaded key

Return type

AbstractKey

save_pkcs1(format='PEM') → bytes

Saves the key in PKCS#1 DER or PEM format.

Parameters

format (str) – the format to save; ‘PEM’ or ‘DER’

Returns

the DER- or PEM-encoded key.

Return type

bytes

unblind(blinded: int, r: int) → int

Performs blinding on the message using random number ‘r’.

Parameters
  • blinded – the blinded message, as integer, to unblind.

  • r – the random number to unblind with.

Returns

the original message.

The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29

8.3. Exceptions

class rsa.pkcs1.CryptoError(Exception)

Base class for all exceptions in this module.

class rsa.pkcs1.DecryptionError(CryptoError)

Raised when decryption fails.

class rsa.pkcs1.VerificationError(CryptoError)

Raised when verification fails.

8.3.1. The VARBLOCK file format

Warning

The VARBLOCK format is NOT recommended for general use, has been deprecated since Python-RSA 3.4, and was removed in version 4.0. It’s vulnerable to a number of attacks. See Working with big files for more information.

The VARBLOCK file format allows us to encrypt files that are larger than the RSA key. The format is as follows; || denotes byte string concatenation:

VARBLOCK := VERSION || BLOCK || BLOCK || ...

VERSION := 1

BLOCK := LENGTH || DATA

LENGTH := varint-encoded length of the following data, in bytes

DATA := the data to store in the block

The varint-format was taken from Google’s Protobuf, and allows us to efficiently encode an arbitrarily long integer.

8.4. Module: rsa.core

At the core of the RSA encryption method lie these functions. They both operate on (arbitrarily long) integers only. They probably aren’t of much use to you, but I wanted to document them anyway as they are the core of the entire library.

rsa.core.encrypt_int(message: int, ekey: int, n: int) → int

Encrypts a message using encryption key ‘ekey’, working modulo n

rsa.core.decrypt_int(cyphertext: int, dkey: int, n: int) → int

Decrypts a cypher text using the decryption key ‘dkey’, working modulo n