Skip to content

Latest commit

 

History

History
115 lines (82 loc) · 3.28 KB

util.rst

File metadata and controls

115 lines (82 loc) · 3.28 KB

Crypto.Util package

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

asn1

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

Crypto.Util.RFC1751 module

Crypto.Util.RFC1751

Crypto.Util.strxor module

Fast XOR for byte strings.

Crypto.Util.strxor

Crypto.Util.Counter module

Richer counter functions for CTR cipher mode.

CTR <ctr_mode> is a mode of operation for block ciphers.

The plaintext is broken up in blocks and each block is XOR-ed with a keystream to obtain the ciphertext. The keystream is produced by the encryption of a sequence of counter blocks, which all need to be different to avoid repetitions in the keystream. Counter blocks don't need to be secret.

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

The new function at the module level under Crypto.Cipher instantiates a new CTR cipher object for the relevant base algorithm. Its parameters allow you define a counter block with a fixed structure:

  • an optional, fixed prefix
  • the counter field encoded in big endian mode

The length of the two components can vary, but together they must be as large as the block size (e.g. 16 bytes for AES).

Alternatively, the counter parameter can be used to pass a counter block object (created in advance with the function Crypto.Util.Counter.new()) for a more complex composition:

  • 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:

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

Example of AES-CTR encryption with custom counter:

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

nonce = Random.get_random_bytes(4)
ctr = Counter.new(64, prefix=nonce, suffix=b'ABCD', 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)

Crypto.Util.Counter

Crypto.Util.number module

Crypto.Util.number