0
# Exception Handling
1
2
Comprehensive exception hierarchy for different error conditions in Argon2 operations, providing specific error types for verification failures, hashing errors, invalid parameters, and platform-specific limitations.
3
4
## Capabilities
5
6
### Base Exception
7
8
Root exception class for all Argon2-related errors.
9
10
```python { .api }
11
class Argon2Error(Exception):
12
"""
13
Superclass of all argon2 exceptions.
14
15
Never thrown directly - used as base class for specific error types.
16
Catch this to handle any Argon2-related error.
17
"""
18
```
19
20
#### Usage Example
21
22
```python
23
from argon2 import PasswordHasher
24
from argon2.exceptions import Argon2Error
25
26
ph = PasswordHasher()
27
28
try:
29
result = ph.hash("password")
30
ph.verify(result, "password")
31
except Argon2Error as e:
32
print(f"Argon2 operation failed: {e}")
33
```
34
35
### Verification Errors
36
37
Exceptions raised during password verification operations.
38
39
```python { .api }
40
class VerificationError(Argon2Error):
41
"""
42
Verification failed for unspecified reasons.
43
44
Base class for verification-related errors. The original error
45
message from Argon2 C library is available in args[0].
46
"""
47
48
class VerifyMismatchError(VerificationError):
49
"""
50
The secret does not match the hash.
51
52
Raised when password verification fails because the provided
53
password does not match the stored hash. This is the most
54
common verification error during normal operation.
55
"""
56
```
57
58
#### Usage Example
59
60
```python
61
from argon2 import PasswordHasher
62
from argon2.exceptions import VerifyMismatchError, VerificationError
63
64
ph = PasswordHasher()
65
stored_hash = ph.hash("correct_password")
66
67
# Handle specific verification failures
68
try:
69
ph.verify(stored_hash, "wrong_password")
70
except VerifyMismatchError:
71
print("Invalid password - access denied")
72
except VerificationError as e:
73
print(f"Verification failed due to error: {e}")
74
75
# Handle all verification errors together
76
try:
77
ph.verify(stored_hash, user_input)
78
print("Login successful")
79
except VerificationError:
80
print("Login failed")
81
```
82
83
### Hashing Errors
84
85
Exception raised when hash generation fails.
86
87
```python { .api }
88
class HashingError(Argon2Error):
89
"""
90
Raised if hashing failed.
91
92
Indicates that the Argon2 hashing operation could not be completed.
93
The original error message from Argon2 C library is available in args[0].
94
95
Common causes:
96
- Invalid parameters (e.g., memory cost too high)
97
- System resource limitations
98
- Memory allocation failures
99
"""
100
```
101
102
#### Usage Example
103
104
```python
105
from argon2 import PasswordHasher
106
from argon2.exceptions import HashingError
107
108
# Attempt hashing with potentially problematic parameters
109
try:
110
ph = PasswordHasher(
111
memory_cost=999999999, # Excessive memory requirement
112
time_cost=1000, # Very high time cost
113
)
114
hash_result = ph.hash("password")
115
except HashingError as e:
116
print(f"Hashing failed: {e}")
117
# Fall back to more conservative parameters
118
ph_safe = PasswordHasher() # Use defaults
119
hash_result = ph_safe.hash("password")
120
```
121
122
### Hash Format Errors
123
124
Exception raised for invalid hash formats.
125
126
```python { .api }
127
class InvalidHashError(ValueError):
128
"""
129
Raised if the hash is invalid before passing it to Argon2.
130
131
Indicates that the hash string format is so malformed that
132
it cannot be processed by the Argon2 library. This includes:
133
- Incorrect hash string structure
134
- Missing required components
135
- Invalid encoding
136
"""
137
138
# Deprecated alias (still available for compatibility)
139
InvalidHash = InvalidHashError
140
"""
141
Deprecated alias for InvalidHashError.
142
Use InvalidHashError instead.
143
"""
144
```
145
146
#### Usage Example
147
148
```python
149
from argon2 import PasswordHasher
150
from argon2.exceptions import InvalidHashError
151
152
ph = PasswordHasher()
153
154
invalid_hashes = [
155
"not_a_hash_at_all",
156
"$argon2id$invalid$format",
157
"",
158
"$argon2id$v=19$m=65536,t=3,p=4", # Missing salt and hash
159
]
160
161
for bad_hash in invalid_hashes:
162
try:
163
ph.verify(bad_hash, "password")
164
except InvalidHashError:
165
print(f"Invalid hash format: {bad_hash}")
166
```
167
168
### Platform Limitations
169
170
Exception raised when parameters are not supported on the current platform.
171
172
```python { .api }
173
class UnsupportedParametersError(ValueError):
174
"""
175
Raised if the current platform does not support the parameters.
176
177
Examples:
178
- WebAssembly environments require parallelism=1
179
- Memory-constrained systems may not support high memory costs
180
- Some embedded platforms have threading limitations
181
"""
182
```
183
184
#### Usage Example
185
186
```python
187
from argon2 import PasswordHasher
188
from argon2.exceptions import UnsupportedParametersError
189
190
try:
191
# This may fail in WebAssembly environments
192
ph = PasswordHasher(parallelism=8)
193
except UnsupportedParametersError as e:
194
print(f"Parameters not supported on this platform: {e}")
195
# Fall back to platform-compatible settings
196
ph = PasswordHasher(parallelism=1)
197
198
# Alternative: Use platform-aware defaults
199
from argon2.profiles import get_default_parameters
200
default_params = get_default_parameters() # Automatically adjusts for platform
201
ph = PasswordHasher.from_parameters(default_params)
202
```
203
204
## Error Handling Patterns
205
206
### Comprehensive Error Handling
207
208
Handle all possible Argon2 errors with appropriate fallbacks:
209
210
```python
211
from argon2 import PasswordHasher
212
from argon2.exceptions import (
213
VerifyMismatchError,
214
VerificationError,
215
HashingError,
216
InvalidHashError,
217
UnsupportedParametersError,
218
Argon2Error
219
)
220
221
def safe_hash_password(password: str) -> str:
222
"""Hash password with error handling and fallbacks."""
223
try:
224
ph = PasswordHasher()
225
return ph.hash(password)
226
except UnsupportedParametersError:
227
# Fall back to platform-compatible parameters
228
ph = PasswordHasher(parallelism=1)
229
return ph.hash(password)
230
except HashingError as e:
231
# Log error and use more conservative parameters
232
print(f"Hashing failed, trying conservative settings: {e}")
233
ph = PasswordHasher(memory_cost=32768, time_cost=2)
234
return ph.hash(password)
235
236
def safe_verify_password(hash_str: str, password: str) -> bool:
237
"""Verify password with comprehensive error handling."""
238
try:
239
ph = PasswordHasher()
240
ph.verify(hash_str, password)
241
return True
242
except VerifyMismatchError:
243
# Normal case - wrong password
244
return False
245
except InvalidHashError:
246
# Hash is corrupted/invalid - treat as verification failure
247
print("Warning: Invalid hash format detected")
248
return False
249
except VerificationError as e:
250
# Other verification issues - log but treat as failure
251
print(f"Verification error: {e}")
252
return False
253
```
254
255
### Login System Integration
256
257
Typical integration pattern for authentication systems:
258
259
```python
260
from argon2 import PasswordHasher
261
from argon2.exceptions import VerifyMismatchError, Argon2Error
262
263
def authenticate_user(username: str, password: str) -> bool:
264
"""Authenticate user with proper error handling."""
265
# Retrieve stored hash from database
266
stored_hash = get_user_hash(username)
267
if not stored_hash:
268
return False
269
270
ph = PasswordHasher()
271
272
try:
273
# Verify password
274
ph.verify(stored_hash, password)
275
276
# Check if hash needs updating
277
if ph.check_needs_rehash(stored_hash):
278
new_hash = ph.hash(password)
279
update_user_hash(username, new_hash)
280
print(f"Updated password hash for user: {username}")
281
282
return True
283
284
except VerifyMismatchError:
285
# Wrong password - normal case
286
return False
287
except Argon2Error as e:
288
# Any other Argon2 error - log and deny access
289
print(f"Authentication error for {username}: {e}")
290
return False
291
```
292
293
### Parameter Validation
294
295
Validate parameters before creating PasswordHasher instances:
296
297
```python
298
from argon2 import PasswordHasher, Parameters
299
from argon2.exceptions import UnsupportedParametersError
300
from argon2._utils import validate_params_for_platform
301
302
def create_secure_hasher(
303
time_cost: int = 3,
304
memory_cost: int = 65536,
305
parallelism: int = 4
306
) -> PasswordHasher:
307
"""Create hasher with parameter validation."""
308
309
# Create parameters object for validation
310
params = Parameters(
311
type=Type.ID,
312
version=19,
313
salt_len=16,
314
hash_len=32,
315
time_cost=time_cost,
316
memory_cost=memory_cost,
317
parallelism=parallelism,
318
)
319
320
try:
321
# Validate parameters for current platform
322
validate_params_for_platform(params)
323
return PasswordHasher.from_parameters(params)
324
except UnsupportedParametersError as e:
325
print(f"Parameters not supported: {e}")
326
# Return hasher with platform defaults
327
from argon2.profiles import get_default_parameters
328
return PasswordHasher.from_parameters(get_default_parameters())
329
```