devkitx 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,326 @@
1
+ """Security and hashing utilities for DevKitX.
2
+
3
+ This module provides utilities for password hashing, secret generation,
4
+ data hashing, JWT tokens, and input sanitization.
5
+ """
6
+
7
+ import bcrypt
8
+ import secrets
9
+ import uuid
10
+ import hashlib
11
+ import base64
12
+ import jwt
13
+ import re
14
+ import html
15
+ import time
16
+ from typing import Any
17
+
18
+ __all__ = [
19
+ "hash_password",
20
+ "verify_password",
21
+ "generate_secret_key",
22
+ "generate_uuid",
23
+ "hash_data",
24
+ "generate_jwt_token",
25
+ "verify_jwt_token",
26
+ "sanitize_input",
27
+ ]
28
+
29
+
30
+ def hash_password(password: str) -> str:
31
+ """Hash password using bcrypt algorithm.
32
+
33
+ Args:
34
+ password: Plain text password to hash
35
+
36
+ Returns:
37
+ Bcrypt hashed password as string
38
+
39
+ Example:
40
+ >>> hashed = hash_password("my_secure_password")
41
+ >>> len(hashed) == 60 # bcrypt hashes are always 60 characters
42
+ True
43
+ """
44
+ if not isinstance(password, str):
45
+ raise TypeError("Password must be a string")
46
+
47
+ if not password:
48
+ raise ValueError("Password cannot be empty")
49
+
50
+ # Generate salt and hash password
51
+ salt = bcrypt.gensalt()
52
+ hashed = bcrypt.hashpw(password.encode("utf-8"), salt)
53
+
54
+ return hashed.decode("utf-8")
55
+
56
+
57
+ def verify_password(password: str, hashed: str) -> bool:
58
+ """Verify password against bcrypt hash.
59
+
60
+ Args:
61
+ password: Plain text password to verify
62
+ hashed: Bcrypt hashed password to verify against
63
+
64
+ Returns:
65
+ True if password matches hash, False otherwise
66
+
67
+ Example:
68
+ >>> hashed = hash_password("my_password")
69
+ >>> verify_password("my_password", hashed)
70
+ True
71
+ >>> verify_password("wrong_password", hashed)
72
+ False
73
+ """
74
+ if not isinstance(password, str):
75
+ raise TypeError("Password must be a string")
76
+
77
+ if not isinstance(hashed, str):
78
+ raise TypeError("Hashed password must be a string")
79
+
80
+ if not password:
81
+ raise ValueError("Password cannot be empty")
82
+
83
+ if not hashed:
84
+ raise ValueError("Hashed password cannot be empty")
85
+
86
+ try:
87
+ return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
88
+ except ValueError:
89
+ # Invalid hash format
90
+ return False
91
+
92
+
93
+ def generate_secret_key(length: int = 32) -> str:
94
+ """Generate cryptographically secure secret key.
95
+
96
+ Args:
97
+ length: Length of secret key in bytes (default: 32)
98
+
99
+ Returns:
100
+ Base64-encoded secret key
101
+
102
+ Example:
103
+ >>> key = generate_secret_key()
104
+ >>> len(base64.b64decode(key)) == 32
105
+ True
106
+ >>> key1 = generate_secret_key(16)
107
+ >>> key2 = generate_secret_key(16)
108
+ >>> key1 != key2 # Should be different each time
109
+ True
110
+ """
111
+ if not isinstance(length, int):
112
+ raise TypeError("Length must be an integer")
113
+
114
+ if length <= 0:
115
+ raise ValueError("Length must be positive")
116
+
117
+ if length > 1024:
118
+ raise ValueError("Length cannot exceed 1024 bytes")
119
+
120
+ # Generate cryptographically secure random bytes
121
+ random_bytes = secrets.token_bytes(length)
122
+
123
+ # Encode as base64 for safe string representation
124
+ return base64.b64encode(random_bytes).decode("utf-8")
125
+
126
+
127
+ def generate_uuid() -> str:
128
+ """Generate UUID4 string.
129
+
130
+ Returns:
131
+ UUID4 string in standard format (e.g., '550e8400-e29b-41d4-a716-446655440000')
132
+
133
+ Example:
134
+ >>> uuid_str = generate_uuid()
135
+ >>> len(uuid_str) == 36
136
+ True
137
+ >>> uuid_str.count('-') == 4
138
+ True
139
+ >>> uuid1 = generate_uuid()
140
+ >>> uuid2 = generate_uuid()
141
+ >>> uuid1 != uuid2 # Should be different each time
142
+ True
143
+ """
144
+ return str(uuid.uuid4())
145
+
146
+
147
+ def hash_data(data: bytes | str, algorithm: str = "sha256") -> str:
148
+ """Hash data using specified algorithm.
149
+
150
+ Args:
151
+ data: Data to hash (string or bytes)
152
+ algorithm: Hashing algorithm to use (sha256, sha1, sha512, md5, etc.)
153
+
154
+ Returns:
155
+ Hexadecimal hash string
156
+
157
+ Example:
158
+ >>> hash_data("hello world")
159
+ 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
160
+ >>> hash_data(b"hello world")
161
+ 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
162
+ >>> hash_data("test", "md5")
163
+ '098f6bcd4621d373cade4e832627b4f6'
164
+ """
165
+ if not isinstance(data, (str, bytes)):
166
+ raise TypeError("Data must be string or bytes")
167
+
168
+ if not isinstance(algorithm, str):
169
+ raise TypeError("Algorithm must be a string")
170
+
171
+ # Convert string to bytes if necessary
172
+ if isinstance(data, str):
173
+ data_bytes = data.encode("utf-8")
174
+ else:
175
+ data_bytes = data
176
+
177
+ # Check if algorithm is supported
178
+ try:
179
+ hasher = hashlib.new(algorithm)
180
+ except ValueError:
181
+ available_algorithms = sorted(hashlib.algorithms_available)
182
+ raise ValueError(f"Unsupported algorithm '{algorithm}'. Available: {available_algorithms}")
183
+
184
+ hasher.update(data_bytes)
185
+ return hasher.hexdigest()
186
+
187
+
188
+ def generate_jwt_token(payload: dict[str, Any], secret: str, expires_in: int = 3600) -> str:
189
+ """Generate JWT token with expiration.
190
+
191
+ Args:
192
+ payload: Token payload data
193
+ secret: Secret key for signing the token
194
+ expires_in: Token expiration time in seconds (default: 3600 = 1 hour)
195
+
196
+ Returns:
197
+ JWT token string
198
+
199
+ Example:
200
+ >>> payload = {"user_id": 123, "role": "admin"}
201
+ >>> secret = "my-secret-key"
202
+ >>> token = generate_jwt_token(payload, secret, 3600)
203
+ >>> len(token.split('.')) == 3 # JWT has 3 parts
204
+ True
205
+ """
206
+ if not isinstance(payload, dict):
207
+ raise TypeError("Payload must be a dictionary")
208
+
209
+ if not isinstance(secret, str):
210
+ raise TypeError("Secret must be a string")
211
+
212
+ if not secret:
213
+ raise ValueError("Secret cannot be empty")
214
+
215
+ if not isinstance(expires_in, int):
216
+ raise TypeError("expires_in must be an integer")
217
+
218
+ if expires_in <= 0:
219
+ raise ValueError("expires_in must be positive")
220
+
221
+ # Create a copy of payload to avoid modifying the original
222
+ token_payload = payload.copy()
223
+
224
+ # Add standard JWT claims
225
+ current_time = int(time.time())
226
+ token_payload.update(
227
+ {
228
+ "iat": current_time, # Issued at
229
+ "exp": current_time + expires_in, # Expiration time
230
+ }
231
+ )
232
+
233
+ # Generate and return JWT token
234
+ return jwt.encode(token_payload, secret, algorithm="HS256")
235
+
236
+
237
+ def verify_jwt_token(token: str, secret: str) -> dict[str, Any] | None:
238
+ """Verify and decode JWT token.
239
+
240
+ Args:
241
+ token: JWT token string to verify
242
+ secret: Secret key for verification
243
+
244
+ Returns:
245
+ Decoded payload dictionary if valid, None if invalid or expired
246
+
247
+ Example:
248
+ >>> payload = {"user_id": 123}
249
+ >>> secret = "my-secret-key"
250
+ >>> token = generate_jwt_token(payload, secret, 3600)
251
+ >>> decoded = verify_jwt_token(token, secret)
252
+ >>> decoded["user_id"] == 123
253
+ True
254
+ """
255
+ if not isinstance(token, str):
256
+ raise TypeError("Token must be a string")
257
+
258
+ if not isinstance(secret, str):
259
+ raise TypeError("Secret must be a string")
260
+
261
+ if not token:
262
+ raise ValueError("Token cannot be empty")
263
+
264
+ if not secret:
265
+ raise ValueError("Secret cannot be empty")
266
+
267
+ try:
268
+ # Decode and verify the token
269
+ decoded_payload = jwt.decode(token, secret, algorithms=["HS256"])
270
+ return decoded_payload
271
+ except jwt.ExpiredSignatureError:
272
+ # Token has expired
273
+ return None
274
+ except jwt.InvalidTokenError:
275
+ # Token is invalid (malformed, wrong signature, etc.)
276
+ return None
277
+
278
+
279
+ def sanitize_input(text: str, allowed_chars: str | None = None) -> str:
280
+ """Sanitize user input by removing/escaping dangerous characters.
281
+
282
+ This function provides basic input sanitization by:
283
+ 1. HTML escaping dangerous characters
284
+ 2. Removing or filtering characters based on allowed_chars
285
+ 3. Normalizing whitespace
286
+
287
+ Args:
288
+ text: Input text to sanitize
289
+ allowed_chars: Optional regex pattern of allowed characters.
290
+ If provided, only these characters will be kept.
291
+
292
+ Returns:
293
+ Sanitized text string
294
+
295
+ Example:
296
+ >>> sanitize_input("<script>alert('xss')</script>")
297
+ '&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;'
298
+ >>> sanitize_input("Hello123!", r"[a-zA-Z0-9]")
299
+ 'Hello123'
300
+ >>> sanitize_input(" multiple spaces ")
301
+ 'multiple spaces'
302
+ """
303
+ if not isinstance(text, str):
304
+ raise TypeError("Text must be a string")
305
+
306
+ if allowed_chars is not None and not isinstance(allowed_chars, str):
307
+ raise TypeError("allowed_chars must be a string or None")
308
+
309
+ # Start with the input text
310
+ sanitized = text
311
+
312
+ # HTML escape dangerous characters
313
+ sanitized = html.escape(sanitized, quote=True)
314
+
315
+ # If allowed_chars pattern is provided, filter characters
316
+ if allowed_chars is not None:
317
+ try:
318
+ # Keep only characters that match the allowed pattern
319
+ sanitized = re.sub(f"[^{allowed_chars}]", "", sanitized)
320
+ except re.error:
321
+ raise ValueError(f"Invalid regex pattern in allowed_chars: {allowed_chars}")
322
+
323
+ # Normalize whitespace (collapse multiple spaces into single spaces)
324
+ sanitized = re.sub(r"\s+", " ", sanitized).strip()
325
+
326
+ return sanitized