Skip to content

Commit ce6e303

Browse files
committed
security example has been added
1 parent c8654e0 commit ce6e303

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

17-security/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
This directory contains examples and practices for improving security in Python applications.
3+
4+
## Files
5+
6+
### `password_hashing.py`
7+
This script demonstrates how to hash passwords using bcrypt and how to verify them. Hashing passwords is crucial for protecting user credentials.
8+
9+
#### Usage
10+
To hash a password:
11+
```python
12+
from password_hashing import hash_password
13+
14+
hashed_password = hash_password("your_password")
15+
print(hashed_password)
16+
```
17+
18+
19+
# secure_coding_practices.py
20+
21+
This script provides examples of secure coding practices, including input validation and sanitization. Proper input handling is essential to prevent common security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other types of attacks.
22+
23+
## Usage
24+
25+
### To validate an email address:
26+
27+
```python
28+
import re
29+
def is_valid_email(email: str) -> bool:
30+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
31+
return re.match(pattern, email) is not None
32+
```

17-security/password_hashing.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import hashlib
2+
import os
3+
4+
def hash_password(password: str) -> str:
5+
salt = os.urandom(16)
6+
dk = hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000)
7+
return salt + dk
8+
9+
def verify_password(stored_hash: bytes, password: str) -> bool:
10+
salt = stored_hash[:16]
11+
stored_key = stored_hash[16:]
12+
dk = hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000)
13+
return stored_key == dk
14+
15+
if __name__ == "__main__":
16+
password = "supersecret"
17+
hashed_password = hash_password(password)
18+
print(f"Hashed Password: {hashed_password}")
19+
20+
is_correct = verify_password(hashed_password, password)
21+
print(f"Password Match: {is_correct}")
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import re
2+
3+
def is_valid_email(email: str) -> bool:
4+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
5+
return re.match(pattern, email) is not None
6+
7+
def sanitize_input(user_input: str) -> str:
8+
"""sanitize input to prevent injection attacks."""
9+
return re.sub(r'[^\w\s]', '', user_input)
10+
11+
if __name__ == "__main__":
12+
13+
print(f"Is valid email: {is_valid_email(email)}")
14+
15+
user_input = "DROP TABLE users; --"
16+
sanitized = sanitize_input(user_input)
17+
print(f"Sanitized input: {sanitized}")

0 commit comments

Comments
 (0)