def confirm_login(form_username, form_password): try: user = User.select().where(User.username == form_username).get() argon2.PasswordHasher().verify(user.password, form_password) authorize_user(user) if argon2.PasswordHasher().check_needs_rehash(user.password): print("password needs a rehash!") return True # Might need to auto-rehash and update database? except: flash("Wrong authentifications!") return False
def solve_work(index, work_item, work_item_lock, result_queue, hash_rates): work_count = 0 time_start = time.time() while (True): with work_item_lock: (block, difficulty, limit, pool_address, height) = work_item nonce = base64.b64encode( random.getrandbits(256).to_bytes(32, byteorder='big')).decode('utf-8') nonce = re.sub('[^a-zA-Z0-9]', '', nonce) base = '%s-%s-%s-%s' % (pool_address, nonce, block, difficulty) if height > 10800: ph = argon2.PasswordHasher(time_cost=1, memory_cost=524288, parallelism=1, hash_len=32) else: ph = argon2.PasswordHasher(time_cost=4, memory_cost=16384, parallelism=4, hash_len=32) argon = ph.hash(base) base = base + argon hash = hashlib.sha512(base.encode('utf-8')) for i in range(4): hash = hashlib.sha512(hash.digest()) digest = hashlib.sha512(hash.digest()).hexdigest() m = [digest[i:i + 2] for i in range(0, len(digest), 2)] duration = '%d%d%d%d%d%d%d%d' % (int(m[10], 16), int( m[15], 16), int(m[20], 16), int(m[23], 16), int( m[31], 16), int(m[40], 16), int(m[45], 16), int(m[55], 16)) result = int(duration) // int(difficulty) if result > 0 and result < limit: print("solve_work: #%d found valid nonce: %s, %s, %s @ %s:%s:%s" % (index, nonce, argon, pool_address, duration, difficulty, result)) result_queue.put((nonce, argon, pool_address)) work_count += 1 time_end = time.time() hash_rates[index] = work_count / (time_end - time_start) if work_count == 100: work_count = 0 time_start = time_end if index == 0: print('%f H/s - %d workers' % (sum(hash_rates), len(hash_rates)))
def encrypt_data(data_bytes, password): #Farei uma função q associa uma hash para a senha, e com a has encriptografamos password_hash = argon2.PasswordHasher().hash(password) password_hash = password_hash.encode() encoded_hash = base64.urlsafe_b64encode(password_hash[:32]) encryptor = cryptography.fernet.Fernet(encoded_hash) return encryptor.encrypt(data_bytes)
def check_password(uid, password, function, filename): my_dir = os.path.dirname(os.path.realpath(__file__)) + '/' with open(my_dir + filename, 'r') as f: read_csv= csv.reader(f) check_info = None for row in read_csv: if row[0] == uid: check_info = row break if not check_info: return False elif function == 'pbkdf2': salt = bytes(row[2][2:-1], 'utf-8').decode('unicode-escape').encode('ISO-8859-1') return (hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, int(check_info[3])).hex() == check_info[1]) elif function == 'bcrypt': return bcrypt.checkpw(password.encode('utf-8'), bytes(row[1][2:-1], 'utf-8')) elif function == 'scrypt': salt = bytes(row[2][2:-1], 'utf-8').decode('unicode-escape').encode('ISO-8859-1') return (scrypt.hash(password, salt).hex() == check_info[1]) elif function == 'argon2': try: return (argon2.PasswordHasher().verify(check_info[1].replace('|', ','), password)) except: return False else: print('HashError: Hash function is not implemented') raise SystemExit
class Argon2Scheme(SSHADigestScheme): """ scheme follows this format... argon:salt:hashed """ ph = argon2.PasswordHasher() def _format(self, pw): return b2a_base64(self.ph.hash(pw)) def encrypt(self, pw): pw = str(pw) return self._format(pw) def validate(self, reference, attempt): try: ref = a2b_base64(reference) except binascii.Error: # Not valid base64. return False try: return self.ph.verify(ref, attempt) except argon2.exceptions.Argon2Error: return False
def VerifyPassword(passhash, plaintext): try: ph = argon2.PasswordHasher() ph.verify(passhash, plaintext) except argon2.exceptions.VerificationError as e: return False return True
def solve_work(self): global POOL_URL global BLOCK global DIFFICULTY global HASH_RATE_INTERVAL global HASH_RATES global SUBMITTED_NONCES global FAILED_NONCES global REST work_count = 0 time_start = time.time() while (True): nonce = base64.b64encode(random.getrandbits(256).to_bytes(32, byteorder='big')).decode('utf-8') nonce = re.sub('[^a-zA-Z0-9]', '', nonce) base = '%s-%s-%s-%s' % (POOL_ADDRESS, nonce, BLOCK, DIFFICULTY) ph = argon2.PasswordHasher(time_cost=1, memory_cost=524288, parallelism=1, hash_len=32) argon = ph.hash(base) base = base + argon hash = hashlib.sha512(base.encode('utf-8')) for i in range(4): hash = hashlib.sha512(hash.digest()) digest = hashlib.sha512(hash.digest()).hexdigest() m = [digest[i:i + 2] for i in range(0, len(digest), 2)] duration = '%d%d%d%d%d%d%d%d' % (int(m[10], 16), int(m[15], 16), int(m[20], 16), int(m[23], 16), int(m[31], 16), int(m[40], 16), int(m[45], 16), int(m[55], 16)) result = int(duration) // int(DIFFICULTY) if result > 0 and result <= LIMIT: print("Worker #%d found a valid nonce" % (self.id)) self.submit_nonce(nonce, argon, POOL_ADDRESS) work_count += 1 time_end = time.time() HASH_RATES[self.id] = work_count / (time_end - time_start) if work_count == HASH_RATE_INTERVAL: work_count = 0 time_start = time_end if self.id == 0: print('%.2f H/s - %d worker(s) - %d/%d nonce(s) submitted successfully' % (sum(HASH_RATES), len(HASH_RATES), SUBMITTED_NONCES, SUBMITTED_NONCES + FAILED_NONCES)) if REST > 0: time.sleep(REST) if self.id == 0: self.update_work()
def verify_password(self, input_password): """Verifies that the specified password matches the encoded password in the database.""" # Setup Argon2 hasher password_hasher = argon2.PasswordHasher(hash_len=32) # Verify the input password try: password_hasher.verify(self._password_hash, input_password) except ( argon2.exceptions.VerifyMismatchError, argon2.exceptions.VerificationError, argon2.exceptions.InvalidHash, ): # Password hasher raises exceptions if not correct return False # Rehash password if needed, e.g. if parameters are not up to date if password_hasher.check_needs_rehash(self._password_hash): try: self.password = input_password db.session.commit() except sqlalchemy.exc.SQLAlchemyError as sqlerr: db.session.rollback() flask.current_app.logger.exception(sqlerr) # Password correct return True
def __init__(self): """Hash and verify values.""" self._hasher = argon2.PasswordHasher( parallelism=settings.ARGON2_PARALLELISM, memory_cost=settings.ARGON2_MEMORY_COST, time_cost=settings.ARGON2_TIME_COST, )
def password_hasher(): global _password_hasher if _password_hasher is None: _password_hasher = argon2.PasswordHasher() return _password_hasher
def verify_password(self, password): """Takes in a string password and returns True/False if the password matches the password in the database.""" hasher = argon2.PasswordHasher() if isinstance(password, str): password = password.encode() try: hasher.verify(self.password, password) # If no exception was raised, then the password was correct. # We need to check whether the hash is still valid before returning true. We can only do this here # as this is the only time we have the cleartext password if hasher.check_needs_rehash(self.password): # If it needs rehashing, do so now self.password = hasher.hash(password) db.session.commit() return True except (argon2.exceptions.VerifyMismatchError, argon2.exceptions.VerificationError, argon2.exceptions.InvalidHash): # Password did not match (or something else went wrong) return False
def validation(password): #block to generate hash to validate whether the password is correct or not argon2Hasher = argon2.PasswordHasher(time_cost=16, memory_cost=2**15, parallelism=2, hash_len=32, salt_len=16) hash = argon2Hasher.hash(password) return hash
def main(): # Config cfg = core.config.Config(sys.path[0], "config") private_key_pass = getpass.getpass( prompt=f"Private key password: ") if cfg[ cfg.TOKENS_PRIVATE_KEY_PROTECETD] else None private_key = core.auth.jwt.read_private_key( cfg[cfg.TOKENS_PRIVATE_KEY_PATH], private_key_pass) public_key = core.auth.jwt.read_public_key(cfg[cfg.TOKENS_PUBLIC_KEY_PATH]) tokens_lifetime = isodate.parse_duration(cfg[cfg.TOKENS_LIFETIME]) strict_requests = cfg[cfg.APP_STRICT_REQUESTS] # Core password_hasher = argon2.PasswordHasher() database = connect_db(cfg) # Models m_rooms_bans = models.rooms_bans.RoomsBans(database) m_rooms_users = models.rooms_users.RoomsUsers(database) m_posts = models.posts.Posts(database) m_rooms = models.rooms.Rooms(database, m_rooms_users, m_rooms_bans, m_posts) m_users_bans = models.users_bans.UsersBans(database) m_users = models.users.Users(database, m_users_bans, m_rooms, m_rooms_users, m_rooms_bans, m_posts) # Services s_users = services.users.Users(m_users, public_key, tokens_lifetime) s_request = services.request.Request(s_users, strict_requests) s_auth = services.auth.Auth() # Controllers c_login = controllers.login.Login(m_users, m_users_bans, s_auth, password_hasher, private_key, strict_requests) c_users = controllers.users.Users(m_users, m_users_bans, s_auth, password_hasher, strict_requests) c_users_bans = controllers.users_bans.UsersBans(m_users_bans, s_auth, strict_requests) c_rooms = controllers.rooms.Rooms(m_rooms, m_rooms_bans, m_rooms_users, s_auth, strict_requests) c_rooms_bans = controllers.rooms_bans.RoomsBans(m_rooms_bans, m_rooms, m_rooms_users, s_auth, strict_requests) c_rooms_users = controllers.rooms_users.RoomsUsers(m_rooms_users, m_rooms, m_rooms_bans, s_auth, strict_requests) c_posts = controllers.posts.Posts(m_posts, m_rooms, m_rooms_users, m_rooms_bans, s_auth, strict_requests) # App app = flask.Flask(__name__) CORS(app) app.json_encoder = AppJsonEncoder # noinspection PyProtectedMember,PyTypeChecker app._register_error_handler(None, werkzeug.exceptions.HTTPException, handle_exception) # Set up routes app.register_blueprint( routes.routes.init(s_request, c_login, c_users, c_users_bans, c_rooms, c_rooms_bans, c_rooms_users, c_posts)) # Start the app app.run(port=cfg[cfg.APP_PORT], debug=cfg[cfg.APP_DEBUG], threaded=False)
def check_password_hash(password_hash, password): """ Check a password against a given hashed password value. """ password_hasher = argon2.PasswordHasher(hash_len=32) try: return password_hasher.verify(password_hash, password) except argon2.exceptions.VerificationError: return False
def check_password(hash, password): #to check whether entered subject(password) by the user is correct or not argon2Hasher = argon2.PasswordHasher(time_cost=16, memory_cost=2**15, parallelism=2, hash_len=32, salt_len=16) try: return argon2Hasher.verify(hash, password) except: return False
def get_key(self, key_id): data = { "id": key_id, "access": argon2.PasswordHasher().hash(self.access_key) } key = requests.post( 'https://foxedokmsapi.herokuapp.com/api/keys/fetchkey/', json=data).json() return self.decrypt_string(key)
def __init__(self): super(BasicAuthProvider, self).__init__('basic') # Require unsafe_login feature if not config.get_feature('unsafe_login', False): raise NotImplementedError( 'Unsafe login is not permitted on this site!') import argon2 self.argon2_hasher = argon2.PasswordHasher()
def password_hasher(app): password_hasher = argon2.PasswordHasher( time_cost=app.config.get('ARGON2_TIME_COST', argon2.DEFAULT_TIME_COST), memory_cost=app.config.get('ARGON2_MEMORY_COST', argon2.DEFAULT_MEMORY_COST), parallelism=app.config.get('ARGON2_PARALLELISM', argon2.DEFAULT_PARALLELISM), hash_len=app.config.get('ARGON2_HASH_LENGTH', argon2.DEFAULT_HASH_LENGTH), salt_len=app.config.get('ARGON2_SALT_LENGTH', argon2.DEFAULT_RANDOM_SALT_LENGTH), encoding=app.config.get('ARGON2_ENCODING', 'utf-8') ) register_as_extension(app, Extensions.PASSWORD_HASHER, password_hasher)
def basic_auth(username, password, required_scopes=None): import argon2 ph = argon2.PasswordHasher() try: user = User.query.filter_by(name=username).one() ph.verify(user.password, password) except (argon2.exceptions.VerifyMismatchError, NoResultFound): return None return {"sub": user}
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> myhash = passwd('mypassword') >>> passwd_check(myhash, 'mypassword') True >>> passwd_check(myhash, 'otherpassword') False >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True """ if hashed_passphrase.startswith("argon2:"): import argon2 import argon2.exceptions ph = argon2.PasswordHasher() try: return ph.verify(hashed_passphrase[7:], passphrase) except argon2.exceptions.VerificationError: return False try: algorithm, salt, pw_digest = hashed_passphrase.split(":", 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(passphrase.encode("utf-8") + salt.encode("ascii")) return h.hexdigest() == pw_digest
def passwd(passphrase=None, algorithm="argon2"): """Generate hashed password and salt for use in server configuration. In the server configuration, set `c.ServerApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`, or 'argon2'). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword') # doctest: +ELLIPSIS 'argon2:...' """ if passphrase is None: for _ in range(3): p0 = getpass.getpass("Enter password: "******"Verify password: "******"Passwords do not match.") else: raise ValueError("No matching passwords found. Giving up.") if algorithm == "argon2": import argon2 ph = argon2.PasswordHasher( memory_cost=10240, time_cost=10, parallelism=8, ) h_ph = ph.hash(passphrase) return ":".join((algorithm, h_ph)) h = hashlib.new(algorithm) salt = ("%0" + str(salt_len) + "x") % random.getrandbits(4 * salt_len) h.update(passphrase.encode("utf-8") + salt.encode("ascii")) return ":".join((algorithm, salt, h.hexdigest()))
def passwd(passphrase=None, algorithm='argon2'): """Generate hashed password and salt for use in server configuration. In the server configuration, set `c.ServerApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`, or 'argon2'). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword') # doctest: +ELLIPSIS 'argon2:...' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: '******'Verify password: '******'Passwords do not match.') else: raise ValueError('No matching passwords found. Giving up.') if algorithm == 'argon2': import argon2 ph = argon2.PasswordHasher( memory_cost=10240, time_cost=10, parallelism=8, ) h = ph.hash(passphrase) return ':'.join((algorithm, cast_unicode(h, 'ascii'))) h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
def password(self, plaintext_password): """Generate the password hash and save in db.""" pw_hasher = argon2.PasswordHasher(hash_len=32) self._password_hash = pw_hasher.hash(plaintext_password) # User key pair should only be set from here if the password is lost # and all the keys associated with the user should be cleaned up # before setting the password. # This should help the tests for setup as well. if not self.public_key or not self.private_key: self.kd_salt = os.urandom(32) generate_user_key_pair(self, plaintext_password)
def verify(hash2text, password): hash_params = argon2.extract_parameters(hash2text) hash_func = argon2.PasswordHasher(hash_params.time_cost, hash_params.memory_cost, hash_params.parallelism, hash_params.hash_len, hash_params.salt_len, type=hash_params.type) logging.debug('Verificando la validez de la contraseña...') return hash_func.verify(hash2text, password)
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from notebook.auth.security import passwd_check >>> passwd_check('argon2:...', 'mypassword') True >>> passwd_check('argon2:...', 'otherpassword') False >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True """ if hashed_passphrase.startswith('argon2:'): import argon2 import argon2.exceptions ph = argon2.PasswordHasher() try: return ph.verify(hashed_passphrase[7:], passphrase) except argon2.exceptions.VerificationError: return False else: try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii')) return h.hexdigest() == pw_digest
def generate_key_argon2(uid, password): current_line = None my_dir = os.path.dirname(os.path.realpath(__file__)) + '/' with open(my_dir + 'argon2_output.csv', 'r+') as f: while current_line != '': current_line = f.readline() if current_line.split(',')[0] == uid: print('Entry not added: UID already exists') return digest = argon2.PasswordHasher().hash(password).replace(',', '|') f.write(f'{uid},{digest}\n')
def create_session_hash(google_info): hasher = argon2.PasswordHasher( time_cost=6, memory_cost=102400, parallelism=1, hash_len=16, salt_len=16, ) content = json.dumps(google_info, sort_keys=True).encode("utf-8") hash_bytes = hasher.hash(content) hash_ascii = base64.b64encode(hash_bytes.encode("utf-8")).decode("utf-8") return hash_ascii.replace("/", "_").replace("+", "_")
def register_user(username, password): hasher = argon2.PasswordHasher() hashed_password = hasher.hash(password) try: run_sql( "INSERT INTO user (username, password) VALUES (?, ?);", (username, hashed_password), ) return None except apsw.ConstraintError as e: if "UNIQUE" in str(e): return "Username already exists." raise
def gen_api_key_hash(api_key: str, salt: str): """ Generate a hash of the api_key for storing/comparing to db. Args: api_key (str): The cleartext API key (hex). salt (str): The salt to use (hex). Returns: str: SHA512 hash as hex. """ ph = argon2.PasswordHasher() return ph.hash(api_key + salt)
def hash_password(self): """ hash_password(): Initializes an instance of argon2.PasswordHasher from argon2, hashes the password, verifies if the hashing happened properly, raises error if the verification failed, and then returns hashed password if verifications passes. """ ph = argon2.PasswordHasher() hashed_password = ph.hash(self.password) try: ph.verify(hashed_password, self.password) except argon2.exceptions.VerifyMismatchError: raise return hashed_password