Generating keys securely with the secrets and hashlib modules

Generating keys securely with the secrets and hashlib modules

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

Python
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)
  1. Import Statements:

    • from secrets import choice: Imports the choice function from the secrets module. The choice function 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 the string module.

  2. 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.
  3. Password Length:

    • length = 16: Specifies the length of the password to be generated. In this case, the password will have 16 characters.
  4. 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 characters set.
      • The choice(characters) function is called length times to generate a sequence of random characters.
      • ''.join(...) concatenates these characters into a single string, forming the random password.
  5. 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

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() 
  1. Import Statements:

    • import secrets: Imports the secrets module, which provides functions for generating cryptographically secure random numbers and tokens.
    • import string: Imports the string module, which provides sequences of ASCII letters, digits, and punctuation.
  2. Function Definition:

    • generateSecureURL(): This function generates a strong password and a secure URL token.
  3. 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.
  4. Generate Strong Password:

    • The strong password is generated by:
      • Initializing the password variable with characters from different categories: lowercase letter, uppercase letter, digit, and punctuation.
      • Adding 16 additional characters randomly chosen from the src character set to the password.
  5. Print the Strong Password:

    • print("Strong password:", password): Prints the generated strong password to the console.
  6. Generate Secure URL Token:

    • secureURL = "https://www.domain.com/auth/reset=": Initializes the secureURL variable with a prefix for a secure URL.
    • secureURL += secrets.token_urlsafe(16): Appends a secure URL token of length 16 to the secureURL using the secrets.token_urlsafe() function.
  7. Print the Secure URL Token:

    • print("Token secure URL:", secureURL): Prints the generated secure URL token to the console.
  8. Main Execution:

    • if __name__ == "__main__":: Checks if the script is being run as the main program.
    • generateSecureURL(): Calls the generateSecureURL() 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.
Python
import hashlib

password = input("Password:")
hash_password = hashlib.sha512(password.encode())
print("The hash password is:")
print(hash_password.hexdigest())

Password hashing with salt

Python
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")
  1. 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.
  2. 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 True if they match and False otherwise.
  3. Usage:

    • The script prompts the user to enter a new password (new_pass).
    • It then hashes the entered password using hash_password and prints the hashed password.
    • The user is prompted to enter the same password again (old_pass) for verification.
    • The script uses check_password to compare the hashed version of the second input with the originally hashed 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

  1. MD5 (Message Digest Algorithm 5):
Python
   import hashlib
   m = hashlib.md5()
  1. SHA-1 (Secure Hash Algorithm 1):
Python
   import hashlib
   m = hashlib.sha1()
  1. SHA-224:
Python
   import hashlib
   m = hashlib.sha224()
  1. SHA-256:
Python
   import hashlib
   m = hashlib.sha256()
  1. SHA-384:
Python
   import hashlib
   m = hashlib.sha384()
  1. SHA-512:
Python
   import hashlib
   m = hashlib.sha512()
  1. BLAKE2b:
Python
   import hashlib
   m = hashlib.blake2b()
  1. BLAKE2s:
Python
   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:

Python
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

Python
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:

  1. User Input:

    file_name = input("Enter file name:")
    

    The user is prompted to enter the name of the file.

  2. 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.

  3. 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.
Total
3
Shares

Leave a Reply

Previous Post
Steganography techniques for hiding information in images

Steganography techniques for hiding information in images

Next Post
Build TCP, UDP client and TCP server written in Python

Build TCP, UDP client and TCP server written in Python

Related Posts