generated from skills/secure-code-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
60 lines (47 loc) · 2.36 KB
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import binascii
import secrets
import hashlib
import os
import bcrypt
class Random_generator:
# generates a random token using the secrets library for true randomness
def generate_token(self, length=8, alphabet=(
'0123456789'
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
)):
return ''.join(secrets.choice(alphabet) for i in range(length))
# generates salt using the bcrypt library which is a safe implementation
def generate_salt(self, rounds=22):
return bcrypt.gensalt()
# didn't supply the rounds variable to gensalt() because it takes way longer to run
class SHA256_hasher:
# produces the password hash by combining password + salt because hashing
def password_hash(self, password, salt):
password = binascii.hexlify(hashlib.sha256(password.encode()).digest())
password_hash = bcrypt.hashpw(password, salt)
return password_hash.decode('ascii')
# verifies that the hashed password reverses to the plain text version on verification
def password_verification(self, password, password_hash):
password = binascii.hexlify(hashlib.sha256(password.encode()).digest())
password_hash = password_hash.encode('ascii')
return bcrypt.checkpw(password, password_hash)
# a collection of sensitive secrets necessary for the software to operate
PRIVATE_KEY = os.environ.get('PRIVATE_KEY')
PUBLIC_KEY = os.environ.get('PUBLIC_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
PASSWORD_HASHER = 'SHA256_hasher'
"""
Some mistakes are very basic, like choosing a cryptographically-broken algorithm
or committing secret keys directly in your source code.
You are more likely to fall for something more advanced, like using functions that seem random
but produce a weak randomness.
Notice that I used the “random” module, which is designed for modeling and simulation,
not for security or cryptography.
A good practice is to use modules specifically designed and, most importantly,
confirmed by the security community as secure for cryptography-related use cases.
To fix the code, I used the “secrets” module, which provides access to the most secure source of
randomness on my operating system. I also used functions for generating secure tokens and hard-to-guess
URLs.
Other python modules approved and recommended by the security community include argon2 and pbkdf2.
"""