Guest User

Pseudo Code w/ Unit Tests V2

a guest
Jun 19th, 2024
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.76 KB | Help | 0 0
  1. # File: hashing_functions.py
  2.  
  3. import argon2
  4. import scrypt
  5. import bcrypt
  6. import random
  7. import string
  8. import os
  9. import logging
  10. import secrets  # Added for secure random generation
  11. from cryptography.fernet import Fernet
  12. from typing import Optional
  13.  
  14. # Configure logging
  15. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  16. logger = logging.getLogger(__name__)
  17.  
  18. # Function to generate a random salt
  19. def generate_salt(length: int = 16) -> str:
  20.     salt = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))
  21.     logger.info(f'Generated salt: {salt}')
  22.     return salt
  23.  
  24. # Function to get the pepper from environment variables
  25. def get_pepper() -> str:
  26.     pepper_key = os.getenv('PEPPER_KEY')
  27.     if not pepper_key:
  28.         logger.error('PEPPER_KEY environment variable not set.')
  29.         raise EnvironmentError('PEPPER_KEY environment variable not set.')
  30.    
  31.     fernet = Fernet(pepper_key.encode())
  32.     encrypted_pepper = os.getenv('ENCRYPTED_PEPPER')
  33.     if not encrypted_pepper:
  34.         logger.error('ENCRYPTED_PEPPER environment variable not set.')
  35.         raise EnvironmentError('ENCRYPTED_PEPPER environment variable not set.')
  36.    
  37.     decrypted_pepper = fernet.decrypt(encrypted_pepper.encode()).decode()
  38.     logger.info('Decrypted pepper successfully.')
  39.     return decrypted_pepper
  40.  
  41. # Function to hash password using Argon2id
  42. def hash_password(password: str, salt: str, pepper: Optional[str] = None) -> str:
  43.     hash_engine = argon2.PasswordHasher(hash_len=64, salt_len=16, time_cost=2, memory_cost=65536, parallelism=8, hash_type=argon2.Type.ID)
  44.     pepper = pepper or get_pepper()
  45.     hashed = hash_engine.hash(password + salt + pepper)
  46.     logger.info('Hashed password successfully.')
  47.     return hashed
  48.  
  49. # Function to hash mnemonic code using Argon2id
  50. def hash_mnemonic_code(mnemonic_code: str, salt: str, pepper: Optional[str] = None) -> str:
  51.     hash_engine = argon2.PasswordHasher(hash_len=32, salt_len=16, time_cost=2, memory_cost=65536, parallelism=8, hash_type=argon2.Type.ID)
  52.     pepper = pepper or get_pepper()
  53.     hashed = hash_engine.hash(mnemonic_code + salt + pepper)
  54.     logger.info('Hashed mnemonic code successfully.')
  55.     return hashed
  56.  
  57. # Function to hash PIN using scrypt
  58. def hash_pin(pin: str, salt: str, pepper: Optional[str] = None) -> bytes:
  59.     pepper = pepper or get_pepper()
  60.     hashed = scrypt.hash(pin + salt + pepper, salt=salt.encode(), N=16384, r=8, p=1)
  61.     logger.info('Hashed PIN successfully.')
  62.     return hashed
  63.  
  64. # Function to hash username using bcrypt
  65. def hash_username(username: str, salt: str, pepper: Optional[str] = None) -> bytes:
  66.     pepper = pepper or get_pepper()
  67.     hashed = bcrypt.hashpw((username + salt + pepper).encode(), bcrypt.gensalt())
  68.     logger.info('Hashed username successfully.')
  69.     return hashed
  70.  
  71. # Function to generate a random display name
  72. def generate_display_name(length: int = 10) -> str:
  73.     display_name = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))
  74.     logger.info(f'Generated display name: {display_name}')
  75.     return display_name
  76.  
  77. # Example usage
  78. if __name__ == "__main__":
  79.     password = "P@ssw0rd"
  80.     mnemonic_code = "word1 word2 word3 ..."  # 24 words
  81.     pin = "123456789012"
  82.     username = "john_doe"
  83.     display_name = generate_display_name()
  84.  
  85.     salt_password = generate_salt()
  86.     salt_mnemonic = generate_salt()
  87.     salt_pin = generate_salt()
  88.     salt_username = generate_salt()
  89.  
  90.     pepper = get_pepper()
  91.  
  92.     hashed_password = hash_password(password, salt_password, pepper)
  93.     hashed_mnemonic_code = hash_mnemonic_code(mnemonic_code, salt_mnemonic, pepper)
  94.     hashed_pin = hash_pin(pin, salt_pin, pepper)
  95.     hashed_username = hash_username(username, salt_username, pepper)
  96.  
  97.     print(f"Hashed Password: {hashed_password}")
  98.     print(f"Hashed Mnemonic Code: {hashed_mnemonic_code}")
  99.     print(f"Hashed PIN: {hashed_pin}")
  100.     print(f"Hashed Username: {hashed_username}")
  101.     print(f"Display Name: {display_name}")
  102.  
  103. # File: pepper_management.py
  104.  
  105. import os
  106. from cryptography.fernet import Fernet
  107. import logging
  108.  
  109. # Configure logging
  110. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  111. logger = logging.getLogger(__name__)
  112.  
  113. # Function to retrieve the pepper from environment variables or secrets management service
  114. def get_pepper() -> str:
  115.     pepper_key = os.getenv('PEPPER_KEY')
  116.     if not pepper_key:
  117.         logger.error('PEPPER_KEY environment variable not set.')
  118.         raise EnvironmentError('PEPPER_KEY environment variable not set.')
  119.    
  120.     fernet = Fernet(pepper_key.encode())
  121.     encrypted_pepper = os.getenv('ENCRYPTED_PEPPER')
  122.     if not encrypted_pepper:
  123.         logger.error('ENCRYPTED_PEPPER environment variable not set.')
  124.         raise EnvironmentError('ENCRYPTED_PEPPER environment variable not set.')
  125.    
  126.     decrypted_pepper = fernet.decrypt(encrypted_pepper.encode()).decode()
  127.     logger.info('Decrypted pepper successfully.')
  128.     return decrypted_pepper
  129.  
  130. # Example usage
  131. if __name__ == "__main__":
  132.     try:
  133.         pepper = get_pepper()
  134.         print(f"Pepper: {pepper}")
  135.     except EnvironmentError as e:
  136.         logger.error(f"Error: {e}")
  137.         print(f"Error: {e}")
  138.  
  139. # File: test_hashing_functions.py
  140.  
  141. import unittest
  142. from hashing_functions import (
  143.     generate_salt, get_pepper, hash_password, hash_mnemonic_code,
  144.     hash_pin, hash_username, generate_display_name
  145. )
  146. import os
  147. from unittest.mock import patch
  148. import argon2
  149.  
  150. class TestHashingFunctions(unittest.TestCase):
  151.  
  152.     @patch('hashing_functions.get_pepper', return_value='test_pepper')
  153.     def test_hash_password(self, mock_get_pepper):
  154.         salt = generate_salt()
  155.         hashed = hash_password('password', salt)
  156.         self.assertTrue(isinstance(hashed, str))
  157.         self.assertTrue(hashed.startswith('$argon2id$'))
  158.  
  159.     @patch('hashing_functions.get_pepper', return_value='test_pepper')
  160.     def test_hash_mnemonic_code(self, mock_get_pepper):
  161.         salt = generate_salt()
  162.         hashed = hash_mnemonic_code('mnemonic_code', salt)
  163.         self.assertTrue(isinstance(hashed, str))
  164.         self.assertTrue(hashed.startswith('$argon2id$'))
  165.  
  166.     @patch('hashing_functions.get_pepper', return_value='test_pepper')
  167.     def test_hash_pin(self, mock_get_pepper):
  168.         salt = generate_salt()
  169.         hashed = hash_pin('123456', salt)
  170.         self.assertTrue(isinstance(hashed, bytes))
  171.  
  172.     @patch('hashing_functions.get_pepper', return_value='test_pepper')
  173.     def test_hash_username(self, mock_get_pepper):
  174.         salt = generate_salt()
  175.         hashed = hash_username('username', salt)
  176.         self.assertTrue(isinstance(hashed, bytes))
  177.  
  178.     def test_generate_salt(self):
  179.         salt = generate_salt()
  180.         self.assertTrue(isinstance(salt, str))
  181.         self.assertEqual(len(salt), 16)
  182.  
  183.     def test_generate_display_name(self):
  184.         display_name = generate_display_name()
  185.         self.assertTrue(isinstance(display_name, str))
  186.         self.assertEqual(len(display_name), 10)
  187.  
  188. if __name__ == "__main__":
  189.     unittest.main()
  190.  
  191. # File: test_pepper_management.py
  192.  
  193. import unittest
  194. from unittest.mock import patch
  195. from pepper_management import get_pepper
  196.  
  197. class TestPepperManagement(unittest.TestCase):
  198.  
  199.     @patch('pepper_management.os.getenv')
  200.     @patch('pepper_management.Fernet.decrypt')
  201.     def test_get_pepper(self, mock_decrypt, mock_getenv):
  202.         mock_getenv.side_effect = lambda key: {
  203.             'PEPPER_KEY': 'test_pepper_key',
  204.             'ENCRYPTED_PEPPER': 'test_encrypted_pepper'
  205.         }.get(key)
  206.         mock_decrypt.return_value = b'test_pepper'
  207.         pepper = get_pepper()
  208.         self.assertEqual(pepper, 'test_pepper')
  209.  
  210. if __name__ == "__main__":
  211.     unittest.main()
  212.  
Advertisement
Add Comment
Please, Sign In to add comment