8. Reference

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

8.1. Functions

rsa.encrypt(message, pub_key)

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 = '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, priv_key)

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('hello', pub_key)
>>> decrypt(crypto, priv_key)
'hello'

And with binary data:

>>> crypto = encrypt('\x00\x00\x00\x00\x01', pub_key)
>>> decrypt(crypto, priv_key)
'\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('hello', pub_key)
>>> crypto = crypto[0:5] + 'X' + crypto[6:] # change a byte
>>> decrypt(crypto, priv_key)
Traceback (most recent call last):
...
DecryptionError: Decryption failed
rsa.sign(message, priv_key, hash)

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 – the hash method used on the message. Use ‘MD5’, ‘SHA-1’, ‘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, signature, pub_key)

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.

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.
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

class rsa.PublicKey(n, e)

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 accesss 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
load_pkcs1(keyfile, format='PEM')

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

Parameters:
  • keyfile – contents of a DER- or PEM-encoded file that contains the public key.
  • format – the format of the file to load; ‘PEM’ or ‘DER’
Returns:

a PublicKey object

classmethod load_pkcs1_openssl_der(keyfile)

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

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

@return: a PublicKey object

classmethod load_pkcs1_openssl_pem(keyfile)

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.

@param keyfile: contents of a PEM-encoded file that contains the public
key, from OpenSSL.

@return: a PublicKey object

save_pkcs1(format='PEM')

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

Parameters:format – the format to save; ‘PEM’ or ‘DER’
Returns:the DER- or PEM-encoded public key.
class rsa.PrivateKey(n, e, d, p, q, exp1=None, exp2=None, coef=None)

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 accesss is faster, though.

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

exp1, exp2 and coef don’t have to be given, they will be calculated:

>>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
>>> pk.exp1
55063
>>> pk.exp2
10095
>>> pk.coef
50797

If you give exp1, exp2 or coef, they will be used as-is:

>>> pk = PrivateKey(1, 2, 3, 4, 5, 6, 7, 8)
>>> pk.exp1
6
>>> pk.exp2
7
>>> pk.coef
8
load_pkcs1(keyfile, format='PEM')

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

Parameters:
  • keyfile – contents of a DER- or PEM-encoded file that contains the public key.
  • format – the format of the file to load; ‘PEM’ or ‘DER’
Returns:

a PublicKey object

save_pkcs1(format='PEM')

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

Parameters:format – the format to save; ‘PEM’ or ‘DER’
Returns:the DER- or PEM-encoded public key.

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.4. Module: rsa.bigfile

The rsa.bigfile module contains functions for encrypting and decrypting files that are larger than the RSA key. See Working with big files for more information.

rsa.bigfile.encrypt_bigfile(infile, outfile, pub_key)

Encrypts a file, writing it to ‘outfile’ in VARBLOCK format.

Parameters:
  • infile – file-like object to read the cleartext from
  • outfile – file-like object to write the crypto in VARBLOCK format to
  • pub_keyrsa.PublicKey to encrypt with
rsa.bigfile.decrypt_bigfile(infile, outfile, priv_key)

Decrypts an encrypted VARBLOCK file, writing it to ‘outfile’

Parameters:
  • infile – file-like object to read the crypto in VARBLOCK format from
  • outfile – file-like object to write the cleartext to
  • priv_keyrsa.PrivateKey to decrypt with

8.4.1. The VARBLOCK file format

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.5. 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, ekey, n)

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

rsa.core.decrypt_int(cyphertext, dkey, n)

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