0
# Cryptographic Hashing
1
2
Comprehensive collection of cryptographic hash functions, message authentication codes, and extendable output functions. Includes traditional algorithms like SHA and MD families, modern SHA-3 variants, and specialized functions for advanced cryptographic protocols.
3
4
## Capabilities
5
6
### SHA Family Hash Functions
7
8
The Secure Hash Algorithm family providing strong cryptographic hashing with different output sizes and security levels.
9
10
```python { .api }
11
# SHA-1 (legacy, avoid for new applications)
12
def SHA1.new(data=None):
13
"""Create SHA-1 hash object (160-bit output)."""
14
15
# SHA-2 Family (recommended)
16
def SHA224.new(data=None):
17
"""Create SHA-224 hash object (224-bit output)."""
18
19
def SHA256.new(data=None):
20
"""Create SHA-256 hash object (256-bit output)."""
21
22
def SHA384.new(data=None):
23
"""Create SHA-384 hash object (384-bit output)."""
24
25
def SHA512.new(data=None):
26
"""Create SHA-512 hash object (512-bit output)."""
27
28
# Common hash object interface
29
class SHA256Hash:
30
def update(self, data: bytes) -> None:
31
"""Add data to the hash computation."""
32
33
def digest(self) -> bytes:
34
"""Return the digest as bytes."""
35
36
def hexdigest(self) -> str:
37
"""Return the digest as hex string."""
38
39
def copy(self):
40
"""Create a copy of the hash object."""
41
42
digest_size: int # Output size in bytes
43
block_size: int # Internal block size
44
```
45
46
### SHA-3 Family
47
48
The latest SHA-3 standard providing Keccak-based hashing with resistance to length extension attacks.
49
50
```python { .api }
51
def SHA3_224.new(data=None, update_after_digest=False):
52
"""
53
Create SHA3-224 hash object.
54
55
Parameters:
56
- data (bytes): Initial data to hash
57
- update_after_digest (bool): Allow updates after digest() called
58
59
Returns:
60
SHA3-224 hash object (224-bit output)
61
"""
62
63
def SHA3_256.new(data=None, update_after_digest=False):
64
"""Create SHA3-256 hash object (256-bit output)."""
65
66
def SHA3_384.new(data=None, update_after_digest=False):
67
"""Create SHA3-384 hash object (384-bit output)."""
68
69
def SHA3_512.new(data=None, update_after_digest=False):
70
"""Create SHA3-512 hash object (512-bit output)."""
71
```
72
73
### BLAKE2 Hash Functions
74
75
High-performance cryptographic hash functions optimized for software implementations, faster than SHA-2 while providing equivalent security.
76
77
```python { .api }
78
def BLAKE2b.new(**kwargs):
79
"""
80
Create BLAKE2b hash object (up to 512-bit output).
81
82
Parameters:
83
- digest_bits (int): Output size in bits (default: 512)
84
- key (bytes): Optional key for keyed hashing
85
- salt (bytes): Optional salt
86
- person (bytes): Optional personalization
87
- data (bytes): Initial data
88
89
Returns:
90
BLAKE2b hash object
91
"""
92
93
def BLAKE2s.new(**kwargs):
94
"""Create BLAKE2s hash object (up to 256-bit output)."""
95
```
96
97
### MD Family (Legacy)
98
99
Message Digest algorithms for compatibility with legacy systems. Not recommended for new cryptographic applications.
100
101
```python { .api }
102
def MD2.new(data=None):
103
"""Create MD2 hash object (128-bit output)."""
104
105
def MD4.new(data=None):
106
"""Create MD4 hash object (128-bit output)."""
107
108
def MD5.new(data=None):
109
"""Create MD5 hash object (128-bit output)."""
110
```
111
112
### RIPEMD
113
114
RIPEMD-160 hash function designed as an alternative to SHA-1.
115
116
```python { .api }
117
def RIPEMD160.new(data=None):
118
"""Create RIPEMD-160 hash object (160-bit output)."""
119
```
120
121
### Extendable Output Functions (XOF)
122
123
Functions that can produce variable-length output, useful for key derivation and other cryptographic protocols.
124
125
```python { .api }
126
# SHAKE (SHA-3 based XOF)
127
def SHAKE128.new(data=None):
128
"""
129
Create SHAKE128 XOF object.
130
131
Methods:
132
- update(data): Add input data
133
- read(length): Extract output bytes
134
"""
135
136
def SHAKE256.new(data=None):
137
"""Create SHAKE256 XOF object."""
138
139
# Customizable SHAKE (cSHAKE)
140
def cSHAKE128.new(data=None, custom=None):
141
"""
142
Create cSHAKE128 XOF with customization.
143
144
Parameters:
145
- data (bytes): Initial input data
146
- custom (bytes): Customization string
147
"""
148
149
def cSHAKE256.new(data=None, custom=None):
150
"""Create cSHAKE256 XOF with customization."""
151
152
# TurboSHAKE (high-performance XOF)
153
def TurboSHAKE128.new(domain_sep=0x1F):
154
"""Create TurboSHAKE128 XOF with domain separation."""
155
156
def TurboSHAKE256.new(domain_sep=0x1F):
157
"""Create TurboSHAKE256 XOF with domain separation."""
158
159
# KangarooTwelve (K12) - extremely fast XOF
160
def KangarooTwelve.new(custom=b""):
161
"""Create KangarooTwelve XOF with customization string."""
162
```
163
164
### Message Authentication Codes (MAC)
165
166
Cryptographic functions that provide both data integrity and authenticity verification using a secret key.
167
168
```python { .api }
169
# HMAC - Hash-based MAC
170
def HMAC.new(key, msg=b"", digestmod=None):
171
"""
172
Create HMAC object for message authentication.
173
174
Parameters:
175
- key (bytes): Secret key
176
- msg (bytes): Initial message data
177
- digestmod: Hash algorithm (default: MD5, recommend SHA256)
178
179
Returns:
180
HMAC object with update/digest/verify methods
181
"""
182
183
class HMAC:
184
def update(self, data: bytes) -> None:
185
"""Add data to MAC computation."""
186
187
def digest(self) -> bytes:
188
"""Return MAC value as bytes."""
189
190
def hexdigest(self) -> str:
191
"""Return MAC value as hex string."""
192
193
def verify(self, mac_tag: bytes) -> None:
194
"""Verify MAC tag (raises ValueError if invalid)."""
195
196
def copy(self):
197
"""Create copy of HMAC object."""
198
199
# CMAC - Cipher-based MAC
200
def CMAC.new(key, msg=None, ciphermod=None, cipher_params=None, mac_len=None):
201
"""
202
Create CMAC object using block cipher.
203
204
Parameters:
205
- key (bytes): Secret key
206
- msg (bytes): Initial message
207
- ciphermod: Cipher module (e.g., AES)
208
- cipher_params (dict): Additional cipher parameters
209
- mac_len (int): MAC length in bytes
210
211
Returns:
212
CMAC object with update/digest/verify methods
213
"""
214
215
# Poly1305 - High-speed MAC
216
def Poly1305.new(key, nonce=None, cipher=None):
217
"""
218
Create Poly1305 MAC object.
219
220
Parameters:
221
- key (bytes): 32-byte secret key
222
- nonce (bytes): Nonce for cipher mode
223
- cipher: Optional cipher for one-time key derivation
224
225
Returns:
226
Poly1305 MAC object
227
"""
228
```
229
230
### Specialized Hash Functions
231
232
Advanced hash functions for specific cryptographic protocols and applications.
233
234
```python { .api }
235
# KMAC - Keccak-based MAC and PRF
236
def KMAC128.new(key, custom=b""):
237
"""
238
Create KMAC128 object (Keccak-based MAC).
239
240
Parameters:
241
- key (bytes): Secret key
242
- custom (bytes): Customization string
243
244
Returns:
245
KMAC object with update/digest methods and variable output
246
"""
247
248
def KMAC256.new(key, custom=b""):
249
"""Create KMAC256 object."""
250
251
# TupleHash - Hash tuples of strings
252
def TupleHash128.new(custom=b""):
253
"""
254
Create TupleHash128 for hashing tuples.
255
256
Methods:
257
- update(data_tuple): Hash tuple of byte strings
258
- digest(length): Get fixed-length output
259
"""
260
261
def TupleHash256.new(custom=b""):
262
"""Create TupleHash256 for hashing tuples."""
263
```
264
265
## Usage Patterns
266
267
### Basic Hashing
268
```python
269
from Crypto.Hash import SHA256
270
271
# Single-step hashing
272
hash_obj = SHA256.new(b"data to hash")
273
digest = hash_obj.digest()
274
275
# Incremental hashing
276
hash_obj = SHA256.new()
277
hash_obj.update(b"first chunk")
278
hash_obj.update(b"second chunk")
279
final_digest = hash_obj.digest()
280
```
281
282
### Message Authentication
283
```python
284
from Crypto.Hash import HMAC, SHA256
285
286
# HMAC for message authentication
287
key = b"secret_key"
288
message = b"message to authenticate"
289
hmac_obj = HMAC.new(key, message, SHA256)
290
mac_tag = hmac_obj.digest()
291
292
# Verification
293
hmac_obj = HMAC.new(key, message, SHA256)
294
try:
295
hmac_obj.verify(mac_tag)
296
print("Message is authentic")
297
except ValueError:
298
print("Message authentication failed")
299
```
300
301
### Extendable Output Functions
302
```python
303
from Crypto.Hash import SHAKE256
304
305
# Variable-length output
306
shake = SHAKE256.new()
307
shake.update(b"input data")
308
output1 = shake.read(32) # Get 32 bytes
309
output2 = shake.read(64) # Get another 64 bytes
310
```
311
312
## Common Hash Object Interface
313
314
All hash objects implement a consistent interface:
315
316
```python { .api }
317
class HashObjectInterface:
318
def update(self, data: bytes) -> None:
319
"""Add data to hash computation."""
320
321
def digest(self) -> bytes:
322
"""Get hash digest as bytes."""
323
324
def hexdigest(self) -> str:
325
"""Get hash digest as hex string."""
326
327
def copy(self):
328
"""Create copy of hash state."""
329
330
digest_size: int # Output size in bytes
331
block_size: int # Internal block size in bytes
332
```
333
334
## Error Handling
335
336
- `ValueError`: Invalid key size, parameters, or verification failure
337
- `TypeError`: Incorrect parameter types
338
- Hash function specific exceptions for invalid states or operations