The secrets module in Python is designed for generating cryptographically secure random numbers suitable for managing sensitive data such as passwords, account authentication, security tokens, etc.
Generating keys securely with the secrets module
from secrets import choice
from string import ascii_letters, ascii_uppercase, digits
characters = ascii_letters + ascii_uppercase + digits
length = 16
random_password= ''.join(choice(characters) for character in range(length))
print("The password generated is:", random_password)-
Import Statements:
-
from secrets import choice: Imports thechoicefunction from thesecretsmodule. Thechoicefunction is used to make a random selection from a sequence. -
from string import ascii_letters, ascii_uppercase, digits: Imports the sequences of ASCII letters (both lowercase and uppercase) and digits from thestringmodule.
-
-
Character Set:
characters = ascii_letters + ascii_uppercase + digits: Creates a character set by concatenating ASCII letters (both lowercase and uppercase) and digits. This set is used to generate the random password.
-
Password Length:
length = 16: Specifies the length of the password to be generated. In this case, the password will have 16 characters.
-
Generating the Random Password:
random_password = ''.join(choice(characters) for character in range(length)):- Uses a generator expression to create a sequence of randomly chosen characters from the
charactersset. - The
choice(characters)function is calledlengthtimes to generate a sequence of random characters. ''.join(...)concatenates these characters into a single string, forming the random password.
- Uses a generator expression to create a sequence of randomly chosen characters from the
-
Print the Result:
print("The password generated is:", random_password): Prints the generated random password to the console.
A function, generateSecureURL(), that generates a strong password and a secure URL token using the secrets module in Python
import secrets
import string
def generateSecureURL():
src = string.ascii_letters + string.digits + string.punctuation
password = secrets.choice(string.ascii_lowercase)
password += secrets.choice(string.ascii_uppercase)
password += secrets.choice(string.digits)
password += secrets.choice(string.punctuation)
for i in range (16):
password += secrets.choice(src)
print ("Strong password:", password)
secureURL = "https://www.domain.com/auth/reset="
secureURL += secrets.token_urlsafe(16)
print("Token secure URL:", secureURL)
if __name__ == "__main__":
generateSecureURL() -
Import Statements:
import secrets: Imports thesecretsmodule, which provides functions for generating cryptographically secure random numbers and tokens.import string: Imports thestringmodule, which provides sequences of ASCII letters, digits, and punctuation.
-
Function Definition:
generateSecureURL(): This function generates a strong password and a secure URL token.
-
Character Set Initialization:
src = string.ascii_letters + string.digits + string.punctuation: Creates a character set (src) by concatenating ASCII letters (both lowercase and uppercase), digits, and punctuation.
-
Generate Strong Password:
- The strong password is generated by:
- Initializing the
passwordvariable with characters from different categories: lowercase letter, uppercase letter, digit, and punctuation. - Adding 16 additional characters randomly chosen from the
srccharacter set to the password.
- Initializing the
- The strong password is generated by:
-
Print the Strong Password:
print("Strong password:", password): Prints the generated strong password to the console.
-
Generate Secure URL Token:
secureURL = "https://www.domain.com/auth/reset=": Initializes thesecureURLvariable with a prefix for a secure URL.secureURL += secrets.token_urlsafe(16): Appends a secure URL token of length 16 to thesecureURLusing thesecrets.token_urlsafe()function.
-
Print the Secure URL Token:
print("Token secure URL:", secureURL): Prints the generated secure URL token to the console.
-
Main Execution:
if __name__ == "__main__":: Checks if the script is being run as the main program.generateSecureURL(): Calls thegenerateSecureURL()function if the script is the main program.
Generating keys securely with the hashlib module
To generate secure hash-based keys, you can use the hashlib module in Python. The hashlib module provides various hash functions, such as SHA-256 and SHA-512, which are commonly used for key generation.
Key Considerations:
- Key Length: SHA-256 produces 256-bit keys, while SHA-512 generates 512-bit keys. Choose based on your security requirements.
- Random Salt: Enhance security by appending a random string (salt) to the input data before hashing.
- Key Storage: Store keys securely, preferably in encrypted form.
- Key Usage: Employ generated keys for various cryptographic tasks like encryption, authentication, and password storage.
Remember:
- Hashing is one-way; you cannot reverse it to retrieve the original input.
- The key’s security depends heavily on the strength of the original secret phrase or password.
- Use
key.hex()for a hexadecimal representation of the key if needed for specific applications.
Additional Tips:
- Employ a password manager to generate and store strong, unique passwords.
- Consider using key derivation functions (KDFs) like PBKDF2 for added security.
- Stay updated on cryptographic best practices to protect sensitive information effectively.
import hashlib
password = input("Password:")
hash_password = hashlib.sha512(password.encode())
print("The hash password is:")
print(hash_password.hexdigest())Password hashing with salt
import uuid
import hashlib
def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
new_pass = input('Enter your password: ')
hashed_password = hash_password(new_pass)
print('The password hash: ' + hashed_password)
old_pass = input('Enter again the password for checking: ')
if check_password(hashed_password, old_pass):
print("Password is correct")
else:
print("Passwords doesn't match")-
hash_password(password)Function:- This function takes a plain-text password as input.
- It generates a random salt using
uuid.uuid4().hex. - It then concatenates the salt and password, hashes the result using SHA-256, and returns the hashed password with the salt as a string in the format:
hashed_password:salt.
-
check_password(hashed_password, user_password)Function:- This function takes a hashed password (in the format
hashed_password:salt) and a user-provided plain-text password. - It extracts the stored salt from the hashed password.
- It hashes the user-provided password with the extracted salt using SHA-256.
- It checks if the computed hash matches the stored hash, returning
Trueif they match andFalseotherwise.
- This function takes a hashed password (in the format
-
Usage:
- The script prompts the user to enter a new password (
new_pass). - It then hashes the entered password using
hash_passwordand prints the hashed password. - The user is prompted to enter the same password again (
old_pass) for verification. - The script uses
check_passwordto compare the hashed version of the second input with the originally hashed password.
- The script prompts the user to enter a new password (
The hashlib module in Python provides access to various hash functions. Here are some of the commonly used hash algorithms available in Python:
Available hash algorithms
- MD5 (Message Digest Algorithm 5):
import hashlib
m = hashlib.md5()- SHA-1 (Secure Hash Algorithm 1):
import hashlib
m = hashlib.sha1()- SHA-224:
import hashlib
m = hashlib.sha224()- SHA-256:
import hashlib
m = hashlib.sha256()- SHA-384:
import hashlib
m = hashlib.sha384()- SHA-512:
import hashlib
m = hashlib.sha512()- BLAKE2b:
import hashlib
m = hashlib.blake2b()- BLAKE2s:
import hashlib
m = hashlib.blake2s()Each of the above hash functions provides a similar interface. You can use the update() method to feed data into the hash object, and then retrieve the hash digest using the hexdigest() method.
Example:
import hashlib
# Create a new hash object using SHA-256
m = hashlib.sha256()
# Update the hash object with data
m.update(b"Hello, World!")
# Get the hexadecimal representation of the hash digest
hash_digest = m.hexdigest()
print("SHA-256 Hash:", hash_digest)Note: MD5 and SHA-1 are considered weak and are not recommended for cryptographic purposes. For cryptographic applications, it’s generally recommended to use SHA-256 or higher. Additionally, when storing passwords, it’s recommended to use key derivation functions like PBKDF2 or bcrypt instead of simple hash functions.
Compute hash digests for a given file using a variety of hashing algorithms
import hashlib
file_name = input("Enter file name:")
file = open(file_name, 'r')
data = file.read().encode('utf-8')
print("-- %s --" % file_name)
print(hashlib.algorithms_available)
for algorithm in hashlib.algorithms_available:
hash = hashlib.new(algorithm)
hash.update(data)
try:
hexdigest = hash.hexdigest()
except TypeError:
hexdigest = hash.hexdigest(128)
print("%s: %s" % (algorithm, hexdigest))This Python script prompts the user to enter a file name, reads the content of the file, and then calculates the hash digest using various available hashing algorithms provided by the hashlib module. Here’s an explanation of the code:
-
User Input:
file_name = input("Enter file name:")The user is prompted to enter the name of the file.
-
Read File Content:
file = open(file_name, 'r') data = file.read().encode('utf-8')The specified file is opened in read mode (
'r'), and its content is read. The content is then encoded as UTF-8 bytes. -
Hash Calculation:
print("-- %s --" % file_name) print(hashlib.algorithms_available) for algorithm in hashlib.algorithms_available: hash = hashlib.new(algorithm) hash.update(data) try: hexdigest = hash.hexdigest() except TypeError: hexdigest = hash.hexdigest(128) print("%s: %s" % (algorithm, hexdigest))- The script prints the name of the file and the available hashing algorithms.
- It iterates over the available hashing algorithms.
- For each algorithm, a new hash object is created (
hashlib.new(algorithm)). - The content of the file is then fed into the hash object using the
update()method. - The hex digest of the hash is calculated using
hexdigest(). - The result, including the algorithm name and hex digest, is printed to the console.