Crypto.Util package

Useful modules that don’t belong in any other package.

Crypto.Util.Padding module

This module provides minimal support for adding and removing standard padding from data. Example:

>>> from Crypto.Util.Padding import pad, unpad
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>>
>>> data = b'Unaligned'   # 9 bytes
>>> key = get_random_bytes(32)
>>> iv = get_random_bytes(16)
>>>
>>> cipher1 = AES.new(key, AES.MODE_CBC, iv)
>>> ct = cipher1.encrypt(pad(data, 16))
>>>
>>> cipher2 = AES.new(key, AES.MODE_CBC, iv)
>>> pt = unpad(cipher2.decrypt(ct), 16)
>>> assert(data == pt)

Crypto.Util.RFC1751 module

Crypto.Util.RFC1751.english_to_key(string):string(2.x)/bytes(2.x)

Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6.

Crypto.Util.RFC1751.key_to_english(key)

key_to_english(key:string(2.x)/bytes(3.x)) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8.

Crypto.Util.strxor module

Fast XOR for byte strings.

Crypto.Util.strxor.strxor(a: str, b: str) str

Return a XOR b. Both a and b must have the same length.

Crypto.Util.strxor.strxor_c(s: str, c: int) str

Return s XOR chr(c). c must be in range(256).

Crypto.Util.Counter module

The Crypto.Util.Counter module provides the functionality to create more complex counter blocks for the CTR cipher mode.

Introduction to counter blocks

CTR (Counter) is a mode of operation for block ciphers. In CTR mode, the ciphertext is generated by dividing the plaintext into blocks and then XOR-ing each block with a unique keystream.

The keystream is produced by encrypting a sequence of counter blocks, which must all be distinct to prevent repetitions in the keystream. Counter blocks themselves do not need to be kept secret. Encryption is done using ECB.

The most straightforward approach to create counter blocks is to include a counter field, and increment it by one within each subsequent counter block.

Creating counter blocks without Counter

The new() function, at the module level under Crypto.Cipher, allows you to create a new CTR cipher object for a specific base algorithm. It provides parameters for defining the structure of the counter block:

  • an optional, fixed prefix

  • the counter field encoded in big endian mode

The combined length of these two components must match the block size of the algorithm being used. For example, in the case of AES, the block size is typically 16 bytes.

Creating counter blocks with Counter

If you need a more complex structure for the counter block, you can define it in advance with the function Crypto.Util.Counter.new(), and then pass it to new() of the cipher with the counter parameter. The counter block can then have:

  • an optional, fixed prefix

  • the counter field, encoded in big endian or little endian mode

  • an optional, fixed suffix

As before, the total length must match the block size.

The counter blocks with a big endian counter will look like this:

../../_images/counter_be.png

The counter blocks with a little endian counter will look like this:

../../_images/counter_le.png

This is an example of AES-CTR encryption with a custom counter:

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random

# The counter block must be
#
# +--------+----------------+--------+
# | nonce  +     counter    +  EFGH  +
# +--------+----------------+--------+
#  4 bytes      8 bytes       4 bytes
nonce = Random.get_random_bytes(4)
ctr = Counter.new(64, prefix=nonce, suffix=b'EFGH', little_endian=True, initial_value=10)
key = b'AES-128 symm key'
plaintext = b'X'*1000000
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
ciphertext = cipher.encrypt(plaintext)

Fast counter functions for CTR cipher modes.

CTR is a chaining mode for symmetric block encryption or decryption. Messages are divideded into blocks, and the cipher operation takes place on each block using the secret key and a unique counter block.

The most straightforward way to fulfil the uniqueness property is to start with an initial, random counter block value, and increment it as the next block is processed.

The block ciphers from Crypto.Cipher (when configured in MODE_CTR mode) invoke a callable object (the counter parameter) to get the next counter block. Unfortunately, the Python calling protocol leads to major performance degradations.

The counter functions instantiated by this module will be invoked directly by the ciphers in Crypto.Cipher. The fact that the Python layer is bypassed lead to more efficient (and faster) execution of CTR cipher modes.

An example of usage is the following:

>>> from Crypto.Cipher import AES
>>> from Crypto.Util import Counter
>>>
>>> pt = b''*1000000
>>> ctr = Counter.new(128)
>>> cipher = AES.new(b''*16, AES.MODE_CTR, counter=ctr)
>>> ct = cipher.encrypt(pt)
undocumented:

__package__

Crypto.Util.Counter.new(nbits, prefix=b'', suffix=b'', initial_value=1, overflow=0, little_endian=False, allow_wraparound=False, disable_shortcut=False)

Create a stateful counter block function suitable for CTR encryption modes.

Each call to the function returns the next counter block. Each counter block is made up by three parts:

prefix || counter value || postfix

The counter value is incremented by one at each call.

Parameters:
nbitsinteger

Length of the desired counter, in bits. It must be a multiple of 8.

prefixbyte string

The constant prefix of the counter block. By default, no prefix is used.

suffixbyte string

The constant postfix of the counter block. By default, no suffix is used.

initial_valueinteger

The initial value of the counter. Default value is 1.

little_endianboolean

If True, the counter number will be encoded in little endian format. If False (default), in big endian format.

allow_wraparoundboolean

If True, the function will raise an OverflowError exception as soon as the counter wraps around. If False (default), the counter will simply restart from zero.

disable_shortcutboolean

If True, do not make ciphers from Crypto.Cipher bypass the Python layer when invoking the counter block function. If False (default), bypass the Python layer.

Returns:

The counter block function.

Crypto.Util.number module

Crypto.Util.number.GCD(x, y)

GCD(x:long, y:long): long Return the GCD of x and y.

Crypto.Util.number.bytes_to_long(s)

bytes_to_long(string) : long Convert a byte string to a long integer.

This is (essentially) the inverse of long_to_bytes().

Crypto.Util.number.getPrime(N, randfunc=None)

getPrime(N:int, randfunc:callable):long Return a random N-bit prime number.

If randfunc is omitted, then Random.new().read is used.

Crypto.Util.number.getRandomInteger(N, randfunc=None)

getRandomInteger(N:int, randfunc:callable):long Return a random number with at most N bits.

If randfunc is omitted, then Random.new().read is used.

This function is for internal use only and may be renamed or removed in the future.

Crypto.Util.number.getRandomNBitInteger(N, randfunc=None)

getRandomInteger(N:int, randfunc:callable):long Return a random number with exactly N-bits, i.e. a random number between 2**(N-1) and (2**N)-1.

If randfunc is omitted, then Random.new().read is used.

This function is for internal use only and may be renamed or removed in the future.

Crypto.Util.number.getRandomNumber(N, randfunc=None)

Deprecated. Use getRandomInteger or getRandomNBitInteger instead.

Crypto.Util.number.getRandomRange(a, b, randfunc=None)

getRandomRange(a:int, b:int, randfunc:callable):long Return a random number n so that a <= n < b.

If randfunc is omitted, then Random.new().read is used.

This function is for internal use only and may be renamed or removed in the future.

Crypto.Util.number.getStrongPrime(N, e=0, false_positive_prob=1e-06, randfunc=None)

getStrongPrime(N:int, e:int, false_positive_prob:float, randfunc:callable):long Return a random strong N-bit prime number. In this context p is a strong prime if p-1 and p+1 have at least one large prime factor. N should be a multiple of 128 and > 512.

If e is provided the returned prime p-1 will be coprime to e and thus suitable for RSA where e is the public exponent.

The optional false_positive_prob is the statistical probability that true is returned even though it is not (pseudo-prime). It defaults to 1e-6 (less than 1:1000000). Note that the real probability of a false-positive is far less. This is just the mathematically provable limit.

randfunc should take a single int parameter and return that many random bytes as a string. If randfunc is omitted, then Random.new().read is used.

Crypto.Util.number.inverse(u, v)

inverse(u:long, v:long):long Return the inverse of u mod v.

Crypto.Util.number.isPrime(N, false_positive_prob=1e-06, randfunc=None)

isPrime(N:long, false_positive_prob:float, randfunc:callable):bool Return true if N is prime.

The optional false_positive_prob is the statistical probability that true is returned even though it is not (pseudo-prime). It defaults to 1e-6 (less than 1:1000000). Note that the real probability of a false-positive is far less. This is just the mathematically provable limit.

If randfunc is omitted, then Random.new().read is used.

Crypto.Util.number.long_to_bytes(n, blocksize=0)

long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string.

If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize.

Crypto.Util.number.size(N)

size(N:long) : int Returns the size of the number N in bits.