def test_pbkdf2(self): try: from _hashlib import pbkdf2_hmac except ImportError: skip("Requires OpenSSL >= 1.1") out = pbkdf2_hmac('sha1', 'password', 'salt', 1) assert out == '0c60c80f961f0e71f3a9b524af6012062fe037a6'.decode('hex') out = pbkdf2_hmac('sha1', 'password', 'salt', 2, None) assert out == 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'.decode('hex')
def test_pbkdf2(self): try: from _hashlib import pbkdf2_hmac except ImportError: skip("Requires OpenSSL >= 1.1") out = pbkdf2_hmac('sha1', 'password', 'salt', 1) assert out == '0c60c80f961f0e71f3a9b524af6012062fe037a6'.decode('hex') out = pbkdf2_hmac('sha1', 'password', 'salt', 2, None) assert out == 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'.decode('hex')
def key_id_creator(variable): """This function create the hash-like mac to check with db and for song id purpose""" variable_b = bytes(variable, 'utf8') dk = pbkdf2_hmac('sha256', variable_b, b'salt', 100000) key_bin = hexlify(dk) return key_bin
def hash_new_password(self, password: str) -> Tuple[bytes, bytes]: """ Hash the provided password with a randomly-generated salt and return the salt and hash to store in the database. :return salt, password hash """ salt = urandom(16) pw_hash = pbkdf2_hmac('sha256', password.encode(), salt, 100000) return salt, pw_hash
def check_password(self, password: str) -> bool: """ Given a previously-stored salt and hash, check whether the password is correct. :param password: key to check :return: bool """ return hmac.compare_digest( bytes.fromhex(self.hash), pbkdf2_hmac('sha1', password.encode(), bytes.fromhex(self.salt), 100000))
def is_correct_password(self, salt: bytes, pw_hash: bytes, password: str) -> bool: """ Function to check pw to unlock db: Given a previously-stored salt and hash, and a password provided by a user trying to log in, check whether the password is correct. :param salt: salt :param pw_hash: hash :param password: check against this user supplied password :return: bool """ return hmac.compare_digest( pw_hash, pbkdf2_hmac('sha256', password.encode(), salt, 100000))
def connection_init(self, ip_address, port): """ The method initiates a connection to the server. :param {str} ip_address: server IP-address. :param {int} port: server port :return: """ # Create a socket (AF_INET - network socket, SOCK_STREAM - work with TCP packets). self.client_sock = socket(AF_INET, SOCK_STREAM) # A timeout is required to free the socket. self.client_sock.settimeout(5) # Connect, 5 connection attempts, set success flag to True if possible. connected = False for attempt in range(5): LOGGER.info(f'Попытка подключения №{attempt + 1}.') try: self.client_sock.connect((ip_address, port)) except (OSError, ConnectionRefusedError): pass else: connected = True break time.sleep(1) # If connection failed, return an exception. if not connected: LOGGER.critical('Не удалось установить соединение с сервером.') raise ServerError('Не удалось установить соединение с сервером.') LOGGER.info(f'Установлено соединение с сервером {ip_address}:{port}.') # Start Authorization Procedure. # Get password hash. password_bytes = self.password.encode(ENCODING) salt = self.username.lower().encode(ENCODING) password_hash = pbkdf2_hmac('sha512', password_bytes, salt, 10000) password_hash_string = hexlify(password_hash) # Get the public key and decode it from bytes. public_key = self.keys.publickey().export_key().decode('ascii') # Authorization on the server. with SOCK_LOCK: presence_dict = CONFIRM_PRESENCE presence_dict[USER] = self.username presence_dict[PUBLIC_KEY] = public_key # Send server confirmation of presence. try: send_message(self.client_sock, presence_dict) server_answer = get_message(self.client_sock) if RESPONSE in server_answer: if server_answer[RESPONSE] == 400 and ERROR in server_answer: LOGGER.error(f'Сервер не смог обработать клиентский' f' запрос. Получен ответ "Response 400:' f' {server_answer[ERROR]}".') raise ServerError(server_answer[ERROR]) elif server_answer[RESPONSE] == 511 and DATA in server_answer: answer_data = server_answer[DATA] answer_hash = hmac.new( password_hash_string, answer_data.encode(ENCODING) ) hash_digest = answer_hash.digest() client_answer = RESPONSE_511 client_answer[DATA] = b2a_base64(hash_digest).decode('ascii') send_message(self.client_sock, client_answer) self.receive_message(get_message(self.client_sock)) except (OSError, JSONDecodeError): LOGGER.critical('Потеряно соединение с сервером.') raise ServerError('Потеряно соединение с сервером.')
def test(): for _ in range(9999): for alg in _hashlib.openssl_md_meth_names: _hashlib.hmac_digest(fstr(), fstr(), alg) try: _hashlib.pbkdf2_hmac(alg, fstr(), fstr(), fint()) _hashlib.pbkdf2_hmac(alg, fstr(), fstr(), fint(), fint()) except ValueError: pass try: _hashlib.scrypt(password=fstr(), salt=fstr(), n=fint(), r=fint(), p=fint()) except (ValueError, TypeError, AttributeError): pass try: do_hash_tests(_hashlib.new(alg)) do_hash_tests(_hashlib.new(alg, fstr())) except ValueError: pass hashes = [ _hashlib.openssl_md5, _hashlib.openssl_sha1, _hashlib.openssl_sha224, _hashlib.openssl_sha256, _hashlib.openssl_sha384, _hashlib.openssl_sha512, _md5.md5, _sha1.sha1, _sha256.sha224, _sha256.sha256, _sha512.sha384, _sha512.sha512, _sha3.sha3_224, _sha3.sha3_384, _sha3.sha3_512, _sha3.shake_128, _sha3.shake_256 ] for h in hashes: do_hash_tests(h()) do_hash_tests(h(fstr())) try: do_hash_tests( _blake2.blake2b(fstr(), digest_size=fint(), key=fstr(), salt=fstr(), person=fstr(), fanout=fint(), depth=fint(), leaf_size=fint(), node_offset=fint(), node_depth=fint(), inner_size=fint(), last_node=fint())) do_hash_tests( _blake2.blake2s(fstr(), digest_size=fint(), key=fstr(), salt=fstr(), person=fstr(), fanout=fint(), depth=fint(), leaf_size=fint(), node_offset=fint(), node_depth=fint(), inner_size=fint(), last_node=fint())) except (ValueError, OverflowError): pass
def __init__(self, key): self.key = pbkdf2_hmac('sha256', key.encode(), b'', 100000)