PyCryptodome is a self-contained Python package of low-level cryptographic primitives
—
Essential utility functions supporting cryptographic operations including padding schemes, counter generation, random number generation, encoding utilities, and number theory operations.
Block cipher padding schemes for ensuring plaintext fits cipher block boundaries with secure padding and unpadding operations.
def pad(data_to_pad, block_size, style='pkcs7'):
"""
Apply padding to data for block cipher operations.
Parameters:
- data_to_pad (bytes): Data to be padded
- block_size (int): Block size in bytes (e.g., 16 for AES)
- style (str): Padding scheme ('pkcs7', 'iso7816', 'ansix923', 'x923')
Returns:
bytes: Padded data
"""
def unpad(padded_data, block_size, style='pkcs7'):
"""
Remove padding from decrypted data.
Parameters:
- padded_data (bytes): Padded data to unpad
- block_size (int): Block size in bytes
- style (str): Padding scheme used
Returns:
bytes: Original unpadded data
Raises:
ValueError: If padding is invalid or corrupted
"""
# Available padding styles
PKCS7_STYLE = 'pkcs7' # PKCS#7 padding (most common)
ISO7816_STYLE = 'iso7816' # ISO 7816-4 padding
ANSIX923_STYLE = 'ansix923' # ANSI X9.23 padding
X923_STYLE = 'x923' # Alias for ANSI X9.23Counter objects for CTR mode encryption providing sequential counter values with customizable parameters.
def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False):
"""
Create a counter object for CTR mode encryption.
Parameters:
- nbits (int): Counter size in bits (multiple of 8)
- prefix (bytes): Fixed prefix bytes
- suffix (bytes): Fixed suffix bytes
- initial_value (int): Starting counter value
- little_endian (bool): Use little-endian byte order
- allow_wraparound (bool): Allow counter to wrap around
Returns:
Counter object with __call__ method returning next counter value
"""
class Counter:
"""Counter object for generating sequential values."""
def __call__(self) -> bytes:
"""
Get next counter value.
Returns:
bytes: Next counter value as bytes
Raises:
OverflowError: If counter overflows and wraparound not allowed
"""Cryptographically secure random number generation for keys, nonces, salts, and other security parameters.
def get_random_bytes(n):
"""
Generate cryptographically secure random bytes.
Parameters:
- n (int): Number of random bytes to generate
Returns:
bytes: Cryptographically secure random bytes
"""
def new(*args, **kwargs):
"""
Create random number generator object.
Returns:
Random number generator with read() method
"""
class _UrandomRNG:
"""Cryptographically secure random number generator."""
def read(self, n: int) -> bytes:
"""Read n random bytes."""
def flush(self) -> None:
"""Flush internal state (no-op for urandom)."""
def reinit(self) -> None:
"""Reinitialize generator (no-op for urandom)."""
def close(self) -> None:
"""Close generator."""Efficient XOR operations for byte strings and constant values, commonly used in cryptographic constructions.
def strxor(term1, term2, output=None):
"""
XOR two byte strings of equal length.
Parameters:
- term1 (bytes): First operand
- term2 (bytes): Second operand
- output (bytearray): Optional output buffer
Returns:
bytes: XOR result
Raises:
ValueError: If strings have different lengths
"""
def strxor_c(term, c, output=None):
"""
XOR byte string with single byte constant.
Parameters:
- term (bytes): Input byte string
- c (int): Byte constant (0-255)
- output (bytearray): Optional output buffer
Returns:
bytes: XOR result with constant
"""Mathematical functions for cryptographic computations including primality testing, random number generation, and modular arithmetic.
def ceil_div(n, d):
"""
Ceiling division - compute ceil(n/d) efficiently.
Parameters:
- n (int): Numerator
- d (int): Denominator
Returns:
int: Ceiling of n divided by d
"""
def size(N):
"""
Get number of bits needed to represent integer N.
Parameters:
- N (int): Integer value
Returns:
int: Number of bits in N
"""
def getRandomInteger(N, randfunc=None):
"""
Generate random integer with exactly N bits.
Parameters:
- N (int): Number of bits
- randfunc (callable): Random function (default: get_random_bytes)
Returns:
int: Random N-bit integer
"""
def getRandomRange(a, b, randfunc=None):
"""
Generate random integer in range [a, b).
Parameters:
- a (int): Lower bound (inclusive)
- b (int): Upper bound (exclusive)
- randfunc (callable): Random function
Returns:
int: Random integer in specified range
"""
def getRandomNBitInteger(N, randfunc=None):
"""
Generate random integer with exactly N bits (MSB always 1).
Parameters:
- N (int): Number of bits (N >= 1)
- randfunc (callable): Random function
Returns:
int: Random N-bit integer with MSB set
"""
def isPrime(N, false_positive_prob=1e-6, randfunc=None):
"""
Test if integer is prime using probabilistic algorithm.
Parameters:
- N (int): Integer to test
- false_positive_prob (float): Maximum false positive probability
- randfunc (callable): Random function
Returns:
bool: True if N is probably prime, False if composite
"""
def getPrime(N, randfunc=None):
"""
Generate random prime number with N bits.
Parameters:
- N (int): Number of bits in prime
- randfunc (callable): Random function
Returns:
int: Random N-bit prime number
"""
def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None):
"""
Generate strong prime suitable for RSA.
Parameters:
- N (int): Number of bits in prime
- e (int): RSA public exponent (0 for any)
- false_positive_prob (float): Primality test accuracy
- randfunc (callable): Random function
Returns:
int: Strong prime suitable for RSA
"""
def inverse(u, v):
"""
Compute modular multiplicative inverse of u modulo v.
Parameters:
- u (int): Integer to invert
- v (int): Modulus
Returns:
int: Inverse of u modulo v
Raises:
ValueError: If gcd(u, v) != 1 (no inverse exists)
"""
def GCD(x, y):
"""
Compute greatest common divisor of x and y.
Parameters:
- x (int): First integer
- y (int): Second integer
Returns:
int: Greatest common divisor
"""
def lcm(x, y):
"""
Compute least common multiple of x and y.
Parameters:
- x (int): First integer
- y (int): Second integer
Returns:
int: Least common multiple
"""Convert cryptographic keys to/from English word sequences for human-readable key representation.
def key_to_english(key):
"""
Convert binary key to English word sequence.
Parameters:
- key (bytes): Binary key data (8 bytes)
Returns:
str: Space-separated English words representing the key
"""
def english_to_key(s):
"""
Convert English word sequence back to binary key.
Parameters:
- s (str): Space-separated English words
Returns:
bytes: Binary key data
Raises:
ValueError: If word sequence is invalid
"""ASN.1 (Abstract Syntax Notation One) utilities for encoding and decoding cryptographic objects in DER format.
class BytesIO_EOF:
"""BytesIO wrapper with EOF detection."""
def read(self, n: int) -> bytes:
"""Read n bytes, detect EOF."""
class DerObject:
"""Base class for ASN.1 DER objects."""
def encode(self) -> bytes:
"""Encode object to DER bytes."""
def decode(self, der_data: bytes, nr_elements=None):
"""Decode DER data into object."""
class DerInteger(DerObject):
"""ASN.1 INTEGER type."""
def __init__(self, value: int = 0):
"""Initialize with integer value."""
class DerBoolean(DerObject):
"""ASN.1 BOOLEAN type."""
def __init__(self, value: bool = False):
"""Initialize with boolean value."""
class DerBitString(DerObject):
"""ASN.1 BIT STRING type."""
def __init__(self, value: bytes = b"", unused_bits: int = 0):
"""Initialize with bit string value."""
class DerOctetString(DerObject):
"""ASN.1 OCTET STRING type."""
def __init__(self, value: bytes = b""):
"""Initialize with octet string value."""
class DerNull(DerObject):
"""ASN.1 NULL type."""
class DerObjectId(DerObject):
"""ASN.1 OBJECT IDENTIFIER type."""
def __init__(self, value: str = ""):
"""Initialize with OID string (e.g., '1.2.840.113549.1.1.1')."""
class DerSequence(DerObject):
"""ASN.1 SEQUENCE type."""
def __init__(self, startSeq=None, implicitTag=None):
"""Initialize sequence container."""
def __getitem__(self, n: int):
"""Get element at index n."""
def __len__(self) -> int:
"""Get number of elements."""
def append(self, item):
"""Add element to sequence."""
class DerSetOf(DerObject):
"""ASN.1 SET OF type."""
def __init__(self, startSeq=None, implicitTag=None):
"""Initialize set container."""from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
# Pad data for AES encryption
plaintext = b"Message that needs padding"
padded = pad(plaintext, AES.block_size, style='pkcs7')
# After decryption, remove padding
decrypted_padded = cipher.decrypt(ciphertext)
original = unpad(decrypted_padded, AES.block_size, style='pkcs7')from Crypto.Util import Counter
from Crypto.Cipher import AES
# Create counter for CTR mode
counter = Counter.new(128, prefix=b"NONCE123", initial_value=1)
# Use with AES-CTR
cipher = AES.new(key, AES.MODE_CTR, counter=counter)
ciphertext = cipher.encrypt(plaintext)from Crypto.Random import get_random_bytes
# Generate random key
key = get_random_bytes(32) # 256-bit key
# Generate random nonce
nonce = get_random_bytes(12) # 96-bit nonce for GCMfrom Crypto.Util.number import getPrime, isPrime, inverse, GCD
# Generate RSA primes
p = getPrime(1024) # 1024-bit prime
q = getPrime(1024) # Another 1024-bit prime
n = p * q # RSA modulus
# Check if number is prime
if isPrime(candidate, false_positive_prob=1e-12):
print("Number is probably prime")
# Compute modular inverse for RSA
e = 65537
phi_n = (p - 1) * (q - 1)
d = inverse(e, phi_n) # Private exponentfrom Crypto.Util.asn1 import DerSequence, DerInteger, DerOctetString
# Create ASN.1 structure
seq = DerSequence()
seq.append(DerInteger(12345))
seq.append(DerOctetString(b"Hello ASN.1"))
# Encode to DER
der_data = seq.encode()
# Decode DER data
decoded_seq = DerSequence()
decoded_seq.decode(der_data)from Crypto.Util.strxor import strxor, strxor_c
# XOR two byte strings
a = b"Hello"
b = b"World"
result = strxor(a, b)
# XOR with constant byte
masked = strxor_c(b"Secret", 0x42)
unmasked = strxor_c(masked, 0x42) # Back to originalValueError: Invalid padding, parameter ranges, or mathematical conditionsTypeError: Incorrect parameter typesOverflowError: Counter overflow or parameter size limitsImportError: Missing system dependencies for specific operationsInstall with Tessl CLI
npx tessl i tessl/pypi-pycryptodome