0
# Utility Functions
1
2
Essential utility functions supporting cryptographic operations including padding schemes, counter generation, random number generation, encoding utilities, and number theory operations.
3
4
## Capabilities
5
6
### Padding Operations
7
8
Block cipher padding schemes for ensuring plaintext fits cipher block boundaries with secure padding and unpadding operations.
9
10
```python { .api }
11
def pad(data_to_pad, block_size, style='pkcs7'):
12
"""
13
Apply padding to data for block cipher operations.
14
15
Parameters:
16
- data_to_pad (bytes): Data to be padded
17
- block_size (int): Block size in bytes (e.g., 16 for AES)
18
- style (str): Padding scheme ('pkcs7', 'iso7816', 'ansix923', 'x923')
19
20
Returns:
21
bytes: Padded data
22
"""
23
24
def unpad(padded_data, block_size, style='pkcs7'):
25
"""
26
Remove padding from decrypted data.
27
28
Parameters:
29
- padded_data (bytes): Padded data to unpad
30
- block_size (int): Block size in bytes
31
- style (str): Padding scheme used
32
33
Returns:
34
bytes: Original unpadded data
35
36
Raises:
37
ValueError: If padding is invalid or corrupted
38
"""
39
40
# Available padding styles
41
PKCS7_STYLE = 'pkcs7' # PKCS#7 padding (most common)
42
ISO7816_STYLE = 'iso7816' # ISO 7816-4 padding
43
ANSIX923_STYLE = 'ansix923' # ANSI X9.23 padding
44
X923_STYLE = 'x923' # Alias for ANSI X9.23
45
```
46
47
### Counter Generation
48
49
Counter objects for CTR mode encryption providing sequential counter values with customizable parameters.
50
51
```python { .api }
52
def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False):
53
"""
54
Create a counter object for CTR mode encryption.
55
56
Parameters:
57
- nbits (int): Counter size in bits (multiple of 8)
58
- prefix (bytes): Fixed prefix bytes
59
- suffix (bytes): Fixed suffix bytes
60
- initial_value (int): Starting counter value
61
- little_endian (bool): Use little-endian byte order
62
- allow_wraparound (bool): Allow counter to wrap around
63
64
Returns:
65
Counter object with __call__ method returning next counter value
66
"""
67
68
class Counter:
69
"""Counter object for generating sequential values."""
70
71
def __call__(self) -> bytes:
72
"""
73
Get next counter value.
74
75
Returns:
76
bytes: Next counter value as bytes
77
78
Raises:
79
OverflowError: If counter overflows and wraparound not allowed
80
"""
81
```
82
83
### Random Number Generation
84
85
Cryptographically secure random number generation for keys, nonces, salts, and other security parameters.
86
87
```python { .api }
88
def get_random_bytes(n):
89
"""
90
Generate cryptographically secure random bytes.
91
92
Parameters:
93
- n (int): Number of random bytes to generate
94
95
Returns:
96
bytes: Cryptographically secure random bytes
97
"""
98
99
def new(*args, **kwargs):
100
"""
101
Create random number generator object.
102
103
Returns:
104
Random number generator with read() method
105
"""
106
107
class _UrandomRNG:
108
"""Cryptographically secure random number generator."""
109
110
def read(self, n: int) -> bytes:
111
"""Read n random bytes."""
112
113
def flush(self) -> None:
114
"""Flush internal state (no-op for urandom)."""
115
116
def reinit(self) -> None:
117
"""Reinitialize generator (no-op for urandom)."""
118
119
def close(self) -> None:
120
"""Close generator."""
121
```
122
123
### String XOR Operations
124
125
Efficient XOR operations for byte strings and constant values, commonly used in cryptographic constructions.
126
127
```python { .api }
128
def strxor(term1, term2, output=None):
129
"""
130
XOR two byte strings of equal length.
131
132
Parameters:
133
- term1 (bytes): First operand
134
- term2 (bytes): Second operand
135
- output (bytearray): Optional output buffer
136
137
Returns:
138
bytes: XOR result
139
140
Raises:
141
ValueError: If strings have different lengths
142
"""
143
144
def strxor_c(term, c, output=None):
145
"""
146
XOR byte string with single byte constant.
147
148
Parameters:
149
- term (bytes): Input byte string
150
- c (int): Byte constant (0-255)
151
- output (bytearray): Optional output buffer
152
153
Returns:
154
bytes: XOR result with constant
155
"""
156
```
157
158
### Number Theory Operations
159
160
Mathematical functions for cryptographic computations including primality testing, random number generation, and modular arithmetic.
161
162
```python { .api }
163
def ceil_div(n, d):
164
"""
165
Ceiling division - compute ceil(n/d) efficiently.
166
167
Parameters:
168
- n (int): Numerator
169
- d (int): Denominator
170
171
Returns:
172
int: Ceiling of n divided by d
173
"""
174
175
def size(N):
176
"""
177
Get number of bits needed to represent integer N.
178
179
Parameters:
180
- N (int): Integer value
181
182
Returns:
183
int: Number of bits in N
184
"""
185
186
def getRandomInteger(N, randfunc=None):
187
"""
188
Generate random integer with exactly N bits.
189
190
Parameters:
191
- N (int): Number of bits
192
- randfunc (callable): Random function (default: get_random_bytes)
193
194
Returns:
195
int: Random N-bit integer
196
"""
197
198
def getRandomRange(a, b, randfunc=None):
199
"""
200
Generate random integer in range [a, b).
201
202
Parameters:
203
- a (int): Lower bound (inclusive)
204
- b (int): Upper bound (exclusive)
205
- randfunc (callable): Random function
206
207
Returns:
208
int: Random integer in specified range
209
"""
210
211
def getRandomNBitInteger(N, randfunc=None):
212
"""
213
Generate random integer with exactly N bits (MSB always 1).
214
215
Parameters:
216
- N (int): Number of bits (N >= 1)
217
- randfunc (callable): Random function
218
219
Returns:
220
int: Random N-bit integer with MSB set
221
"""
222
223
def isPrime(N, false_positive_prob=1e-6, randfunc=None):
224
"""
225
Test if integer is prime using probabilistic algorithm.
226
227
Parameters:
228
- N (int): Integer to test
229
- false_positive_prob (float): Maximum false positive probability
230
- randfunc (callable): Random function
231
232
Returns:
233
bool: True if N is probably prime, False if composite
234
"""
235
236
def getPrime(N, randfunc=None):
237
"""
238
Generate random prime number with N bits.
239
240
Parameters:
241
- N (int): Number of bits in prime
242
- randfunc (callable): Random function
243
244
Returns:
245
int: Random N-bit prime number
246
"""
247
248
def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None):
249
"""
250
Generate strong prime suitable for RSA.
251
252
Parameters:
253
- N (int): Number of bits in prime
254
- e (int): RSA public exponent (0 for any)
255
- false_positive_prob (float): Primality test accuracy
256
- randfunc (callable): Random function
257
258
Returns:
259
int: Strong prime suitable for RSA
260
"""
261
262
def inverse(u, v):
263
"""
264
Compute modular multiplicative inverse of u modulo v.
265
266
Parameters:
267
- u (int): Integer to invert
268
- v (int): Modulus
269
270
Returns:
271
int: Inverse of u modulo v
272
273
Raises:
274
ValueError: If gcd(u, v) != 1 (no inverse exists)
275
"""
276
277
def GCD(x, y):
278
"""
279
Compute greatest common divisor of x and y.
280
281
Parameters:
282
- x (int): First integer
283
- y (int): Second integer
284
285
Returns:
286
int: Greatest common divisor
287
"""
288
289
def lcm(x, y):
290
"""
291
Compute least common multiple of x and y.
292
293
Parameters:
294
- x (int): First integer
295
- y (int): Second integer
296
297
Returns:
298
int: Least common multiple
299
"""
300
```
301
302
### RFC1751 - Key to English Words
303
304
Convert cryptographic keys to/from English word sequences for human-readable key representation.
305
306
```python { .api }
307
def key_to_english(key):
308
"""
309
Convert binary key to English word sequence.
310
311
Parameters:
312
- key (bytes): Binary key data (8 bytes)
313
314
Returns:
315
str: Space-separated English words representing the key
316
"""
317
318
def english_to_key(s):
319
"""
320
Convert English word sequence back to binary key.
321
322
Parameters:
323
- s (str): Space-separated English words
324
325
Returns:
326
bytes: Binary key data
327
328
Raises:
329
ValueError: If word sequence is invalid
330
"""
331
```
332
333
### ASN.1 DER Encoding/Decoding
334
335
ASN.1 (Abstract Syntax Notation One) utilities for encoding and decoding cryptographic objects in DER format.
336
337
```python { .api }
338
class BytesIO_EOF:
339
"""BytesIO wrapper with EOF detection."""
340
341
def read(self, n: int) -> bytes:
342
"""Read n bytes, detect EOF."""
343
344
class DerObject:
345
"""Base class for ASN.1 DER objects."""
346
347
def encode(self) -> bytes:
348
"""Encode object to DER bytes."""
349
350
def decode(self, der_data: bytes, nr_elements=None):
351
"""Decode DER data into object."""
352
353
class DerInteger(DerObject):
354
"""ASN.1 INTEGER type."""
355
356
def __init__(self, value: int = 0):
357
"""Initialize with integer value."""
358
359
class DerBoolean(DerObject):
360
"""ASN.1 BOOLEAN type."""
361
362
def __init__(self, value: bool = False):
363
"""Initialize with boolean value."""
364
365
class DerBitString(DerObject):
366
"""ASN.1 BIT STRING type."""
367
368
def __init__(self, value: bytes = b"", unused_bits: int = 0):
369
"""Initialize with bit string value."""
370
371
class DerOctetString(DerObject):
372
"""ASN.1 OCTET STRING type."""
373
374
def __init__(self, value: bytes = b""):
375
"""Initialize with octet string value."""
376
377
class DerNull(DerObject):
378
"""ASN.1 NULL type."""
379
380
class DerObjectId(DerObject):
381
"""ASN.1 OBJECT IDENTIFIER type."""
382
383
def __init__(self, value: str = ""):
384
"""Initialize with OID string (e.g., '1.2.840.113549.1.1.1')."""
385
386
class DerSequence(DerObject):
387
"""ASN.1 SEQUENCE type."""
388
389
def __init__(self, startSeq=None, implicitTag=None):
390
"""Initialize sequence container."""
391
392
def __getitem__(self, n: int):
393
"""Get element at index n."""
394
395
def __len__(self) -> int:
396
"""Get number of elements."""
397
398
def append(self, item):
399
"""Add element to sequence."""
400
401
class DerSetOf(DerObject):
402
"""ASN.1 SET OF type."""
403
404
def __init__(self, startSeq=None, implicitTag=None):
405
"""Initialize set container."""
406
```
407
408
## Usage Examples
409
410
### Padding Operations
411
```python
412
from Crypto.Util.Padding import pad, unpad
413
from Crypto.Cipher import AES
414
415
# Pad data for AES encryption
416
plaintext = b"Message that needs padding"
417
padded = pad(plaintext, AES.block_size, style='pkcs7')
418
419
# After decryption, remove padding
420
decrypted_padded = cipher.decrypt(ciphertext)
421
original = unpad(decrypted_padded, AES.block_size, style='pkcs7')
422
```
423
424
### Counter for CTR Mode
425
```python
426
from Crypto.Util import Counter
427
from Crypto.Cipher import AES
428
429
# Create counter for CTR mode
430
counter = Counter.new(128, prefix=b"NONCE123", initial_value=1)
431
432
# Use with AES-CTR
433
cipher = AES.new(key, AES.MODE_CTR, counter=counter)
434
ciphertext = cipher.encrypt(plaintext)
435
```
436
437
### Random Number Generation
438
```python
439
from Crypto.Random import get_random_bytes
440
441
# Generate random key
442
key = get_random_bytes(32) # 256-bit key
443
444
# Generate random nonce
445
nonce = get_random_bytes(12) # 96-bit nonce for GCM
446
```
447
448
### Number Theory Operations
449
```python
450
from Crypto.Util.number import getPrime, isPrime, inverse, GCD
451
452
# Generate RSA primes
453
p = getPrime(1024) # 1024-bit prime
454
q = getPrime(1024) # Another 1024-bit prime
455
n = p * q # RSA modulus
456
457
# Check if number is prime
458
if isPrime(candidate, false_positive_prob=1e-12):
459
print("Number is probably prime")
460
461
# Compute modular inverse for RSA
462
e = 65537
463
phi_n = (p - 1) * (q - 1)
464
d = inverse(e, phi_n) # Private exponent
465
```
466
467
### ASN.1 DER Encoding
468
```python
469
from Crypto.Util.asn1 import DerSequence, DerInteger, DerOctetString
470
471
# Create ASN.1 structure
472
seq = DerSequence()
473
seq.append(DerInteger(12345))
474
seq.append(DerOctetString(b"Hello ASN.1"))
475
476
# Encode to DER
477
der_data = seq.encode()
478
479
# Decode DER data
480
decoded_seq = DerSequence()
481
decoded_seq.decode(der_data)
482
```
483
484
### String XOR Operations
485
```python
486
from Crypto.Util.strxor import strxor, strxor_c
487
488
# XOR two byte strings
489
a = b"Hello"
490
b = b"World"
491
result = strxor(a, b)
492
493
# XOR with constant byte
494
masked = strxor_c(b"Secret", 0x42)
495
unmasked = strxor_c(masked, 0x42) # Back to original
496
```
497
498
## Security Considerations
499
500
### Padding Oracle Attacks
501
- Always use authenticated encryption modes when possible
502
- Implement constant-time padding validation
503
- Avoid exposing padding error details to attackers
504
505
### Random Number Quality
506
- PyCryptodome uses OS-provided randomness (urandom)
507
- Suitable for all cryptographic purposes
508
- No manual seeding required
509
510
### Counter Mode Security
511
- Never reuse counter values with the same key
512
- Use proper counter initialization and increment
513
- Consider counter overflow in long-running applications
514
515
### Number Theory Security
516
- Use appropriate bit sizes for cryptographic parameters
517
- Verify prime quality for RSA (use getStrongPrime)
518
- Implement proper parameter validation
519
520
## Error Handling
521
522
- `ValueError`: Invalid padding, parameter ranges, or mathematical conditions
523
- `TypeError`: Incorrect parameter types
524
- `OverflowError`: Counter overflow or parameter size limits
525
- `ImportError`: Missing system dependencies for specific operations