def password(hashed): alphabet = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".upper( ) for a in alphabet: if compare_hash(hashed, crypt.crypt(a, hashed)): return a for a in alphabet: for b in alphabet: if compare_hash(hashed, crypt.crypt(a + b, hashed)): return a + b for a in alphabet: for b in alphabet: for c in alphabet: if compare_hash(hashed, crypt.crypt(a + b + c, hashed)): return a + b + c for a in alphabet: for b in alphabet: for c in alphabet: for d in alphabet: if compare_hash(hashed, crypt.crypt(a + b + c + d, hashed)): return a + b + c + d
def validate_password(self, passwd: str) -> bool: """Check the password against existing credentials. this method _MUST_ return a boolean. @param passwd: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the (possibly) encrypted one in the database. """ if self._password.startswith("$"): # new encryption method if compare_hash(self._password, crypt.crypt(passwd, self._password)): return True else: # legacy encryption method if compare_hash(self._password, self.__encrypt_password_legacy(passwd)): # convert to the new encryption method self._password = self.__encrypt_password(passwd) return True if (self.temp_password is not None and self.temp_password != "" and compare_hash(self.temp_password, crypt.crypt(passwd, self.temp_password))): self._password = self.temp_password self.temp_password = None self.is_password_changed = False return True return False
def login(): if request.method == 'POST': hashed = crypt.crypt(request.form[pass_field], rhashed) if not compare_hash(rhashed, hashed): return 'user or password wrong' else: session[pass_field] = hashed return redirect(url_for('showconfig')) else: phashed = session.get(pass_field) if phashed and compare_hash(rhashed, phashed): return redirect(url_for('showconfig')) return '''
def crack(needle): """Brute force O(n5) algorithm to crack up to a five character Unix DES-based hashed password""" if(needle): alpha = " eEtTaAoOiInNsShHrRdDlLcCuUmMwWfFgGyYpPbBvVkKjJsSqQzZ" alpha_length = len(alpha) needle = sys.argv[1] salt = needle[0:2] haystack = ["" for i in range(5)] for i in range(alpha_length): haystack[4] = alpha[i] for j in range(alpha_length): haystack[3] = alpha[j] for k in range(alpha_length): haystack[2] = alpha[k] for l in range(alpha_length): haystack[1] = alpha[l] for m in range(alpha_length): haystack[0] = alpha[m] # .strip() removes whitespace - very important here current = "".join(haystack).strip() if (compare_hash(crypt.crypt(current, salt), needle)): return print(current) return("Uh oh! Password not found!") else: print("Usage: crack(password)")
def login(): msg = '' # Check if "username" and "password" POST requests exist (user submitted form) if request.method == 'POST' and 'username' in request.form and 'password' in request.form: # Create variables for easy access username = request.form['username'] password = request.form['password'] # Check if account exists using MySQL cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM user WHERE `groups` = "adm" and site = %s', (username,)) # Fetch one record and return result account = cursor.fetchone() # If account exists in accounts table in out database if account: # Create session data, we can access this data in other routes session['loggedin'] = True session['id'] = account['id'] session['username'] = account['site'] cryptedpasswd = account['password'] if compare_hash(crypt.crypt(password, cryptedpasswd), cryptedpasswd): session['gnuu'] = secrets.token_urlsafe(20) cookie = session['gnuu'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('REPLACE INTO sessions (id, site) VALUES (%s,%s)',(cookie, username,)) response = make_response(redirect(url_for('index'))) response.set_cookie("gnuu",cookie) return response else: # Account doesnt exist or username/password incorrect msg = 'Incorrect username/password!' # Show the login form with message (if any) return render_template('login.html', msg=msg)
async def auth_via_next(user, password, env): """Authorization via NEXT stored credentials to access NEXT""" auth_info = await get_auth_by_next_id(user["next_id"]) # check if a password is set on the account. if auth_info["hashed_password"] is None: raise ApiUnauthorized("No password is set on this account.") salt = auth_info.get("salt") hashed_password = auth_info.get("hashed_password") # compare the hashes. check_password = compare_hash( hashed_password, hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100000).hex(), ) if not check_password: raise ApiUnauthorized("Incorrect username or password.") token = generate_api_key(env("SECRET_KEY"), user["next_id"]) return utils.create_authorization_response( token, {"message": "Authorization successful", "next_id": auth_info.get("next_id")}, )
def login(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 _params = request.get_json() _login = _params.get("login", None) _password = _params.get("password", None) if not _login: return jsonify({"msg": "Missing login parameter"}), 400 _user = User.query.filter_by(login=_login).first() if _user is None: return make_response(jsonify({"msg": "forbidden"}), 401) if not _user.isExternalAccount and not _password: return jsonify({"msg": "Bad username or password"}), 401 if _user.isExternalAccount: return jsonify({"jwt": create_access_token(identity=_login)}), 200 if not compare_hash(get_hash(_password), _user.password): return jsonify({"msg": "Bad username or password"}), 401 # Identity can be any data that is json serializable ret = {"jwt": create_access_token(identity=_login)} return jsonify(ret), 200
def login(): """Serves the login page and logs in the user""" if session.get( 'user', None) is not None: # Redirect already atuhenticated users to home return redirect('/') # Initialize form form = LoginForm() # If a valid form is received if form.validate_on_submit(): # Retrieve user by username or email user = User.query.filter((User.Username == form.username.data) | (User.Email == form.username.data)).first() if user: # Found user # Retrieve submitted password password = form.password.data # Compare hashes pw_match = compare_hash(crypt.crypt(password, user.Hash), user.Hash) if pw_match: session['user'] = user.to_dict() return redirect(url_for('index')) else: # No user or email found flash('Unrecognized username and/or password!') return render_template('login.html', title="Login", form=form) else: flash('Unrecognized username and/or password!') return render_template('login.html', title="Login", form=form) return render_template('login.html', title="Login", form=form)
def recebe(): # Recebe confirmacao while (not fim_arq) or len(janela) > 0: # print ('a', fim_arq, 'j', len(janela)) # Espera contato pacote, servidor = udp.recvfrom(1024) # print(pacote) # print('recebe:') # j_print() # secciona pacote em variaveis parte = pacote[:calcsize('L')] r_id = unpack('L', parte)[0] pacote = pacote[calcsize('L'):] parte = pacote[:calcsize('L')] r_seg = unpack('L', parte)[0] pacote = pacote[calcsize('L'):] parte = pacote[:calcsize('I')] r_nseg = unpack('I', parte)[0] pacote = pacote[calcsize('I'):] rhash = pacote.decode('latin1') chash = crypt.crypt(str(r_id) + str(r_seg) + str(r_nseg), rhash) # Libera mensagem confirmada da janela if compare_hash(rhash, chash): if r_id in janela: j_lock.acquire() del janela[r_id] j_lock.release()
def checkPass(generatedPass, userHash): #generate hash from the given password generatedHash = crypt.crypt(generatedPass, "50") #return the boolean value return compare_hash(generatedHash, userHash)
def crack_password(account, word_list, status_bar, password_count): """ Cracks the shadowed password """ shadowed = account.split(":") username = shadowed[0] hashed_pwd = shadowed[1] lindex = hashed_pwd.rfind('$') hash_algorithm = hashed_pwd[1:2] salt = hashed_pwd[3:lindex] algorithm = HASH_ALGORITHMS[hash_algorithm] salt_format = "${}${}$".format(hash_algorithm, salt) with open(word_list, 'r') as raw_passwords: for raw_password in raw_passwords: raw_password = raw_password.strip() crypted = crypt(raw_password, salt_format) if (compare_hash(crypted, shadowed[1])): ua = UnixAccount( username=username, algorithm=algorithm, hash_salt=salt, hashed_password=shadowed[1], raw_password=raw_password) cracked_passwords.append(ua) status_bar.update(password_count) break password_count -= 1 status_bar.update(1)
def validateUsernameAndPassword(realm, username, password): users = config.getLocalConfigValue('users') if username in users and compare_hash( crypt.crypt(password, users[username]), users[username]): return True return False
def login(): username = input('Python login: '******'x' or cryptedpasswd == '*': raise ValueError('no support for shadow passwords') cleartext = getpass.getpass() return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
def CheckUserPassword(DBName, USERName=False, CLEARPassword=False): NewUserName = GetUsername(USERName) if CheckUser(DBName, NewUserName)[0]: return 1, "Bad Username" NewClearPW = GetPassword(CLEARPassword) CurrentPW = DBName.get(NewUserName.encode()) HashedClearPW = crypt.crypt(NewClearPW, CurrentPW.decode()) if compare_hash(HashedClearPW.encode(), CurrentPW): return 0, "Password Check Good" return 1, "Bad Password"
def verifyPw(self, password): if self.id not in userDict.keys() or 'pw' not in userDict[self.id]: return False pw = userDict[self.id]['pw'] if pw.startswith('$'): return compare_hash(pw, crypt(password, pw)) else: return password == pw
def auth_login(login_details): username, passwd = login_details if username is None or passwd is None: print("Enter login details") return False hashed_passwd = REDIS_OBJ.get(username) if compare_hash(hashed_passwd, crypt.crypt(passwd, hashed_passwd)): return True #get_homepage() print("Wrong password") return False
def post(self) -> None: """Attempt login as admin.""" username = self.get_argument("username") password = self.get_argument("password") if (username == options.admin_username and compare_hash( crypt.crypt(password, options.admin_password_hashed), options.admin_password_hashed)): self.set_current_user(username) self.redirect("/admin/") else: self.render("login.html", failed=True)
def recebe(): global erro_total global reenvios_total global tout_total # Recebe confirmacao while (not fim_arq) or len(janela) > 0: # print ('a', fim_arq, 'j', len(janela)) # Espera contato pacote, servidor = udp.recvfrom(1024) # print(pacote) print('recebe:') j_print() # secciona pacote em variaveis parte = pacote[:calcsize('L')] r_id = unpack('L', parte)[0] pacote = pacote[calcsize('L'):] parte = pacote[:calcsize('L')] r_seg = unpack('L', parte)[0] pacote = pacote[calcsize('L'):] parte = pacote[:calcsize('I')] r_nseg = unpack('I', parte)[0] pacote = pacote[calcsize('I'):] rhash = pacote.decode('latin1') chash = crypt.crypt(str(r_id) + str(r_seg) + str(r_nseg), rhash) # Libera mensagem confirmada da janela if compare_hash(rhash, chash): if r_id in janela: j_lock.acquire() grava_log( str(r_id) + ', ' + str(janela[r_id]['tenta']) + ', ' + str(janela[r_id]['erro_e']) + ', ' + str(janela[r_id]['erro_r']) + ', ' + str(janela[r_id]['tout']) + ', ') tout_total += janela[r_id]['tout'] erro_total += janela[r_id]['erro_e'] reenvios_total += janela[r_id]['tenta'] del janela[r_id] j_lock.release() else: print('erro_r =================================') if r_id in janela: j_lock.acquire() janela[r_id]['erro_r'] += 1 print(r_id, janela[r_id]['erro_r']) j_lock.release()
def bruteforce(passwd, dlug): chars = string.ascii_letters posiblekey = product(chars, repeat=dlug) for key in posiblekey: sts = '' for k in key: sts = sts + k if compare_hash(crypt.crypt(sts, passwd), passwd): print("haslo zlamane", sts) break else: sts = ''
def pw_failed(): msg = '' if request.method == 'POST' and 'site' in request.form: errors = validate_input_schema_pw_failed.validate(request.form) if errors: return render_template('pw_failed.html', msg=str(errors)) site = request.form['site'] password = request.form['password'] cryptedpassword = crypt.crypt(password, crypt.METHOD_CRYPT) pwquestion = request.form['pwquestion'] pwanswer = request.form['pwanswer'] cryptedpwanswer = crypt.crypt(pwanswer, crypt.METHOD_CRYPT) status = 0 cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM user WHERE site = %s ', (site, )) account = cursor.fetchone() if account: session['loggedin'] = True clearpwquestion = account['pwquestion'] cryptedpwanswer = account['pwanswer'] if compare_hash(crypt.crypt(pwanswer, cryptedpwanswer), cryptedpwanswer): msg = 'Passwortantwort war richtig' if clearpwquestion == pwquestion: msg = msg + ' + Passwortfrage war richtig' cursor.execute( 'UPDATE user SET failed = 0 WHERE site = %s', (site, )) if password: cursor.execute( 'UPDATE user set password = %s WHERE site = %s', ( cryptedpassword, site, )) msg = msg + " + Passwort geaendert" else: cursor.execute( 'UPDATE user set pwquestion = %s, pwanswer = %s WHERE site = %s', ( pwquestion, cryptedpwanswer, site, )) msg = msg + " + Passwortfrage/antwort geaendert" return render_template('pw_failed.html', msg=msg, site=site) else: msg = 'Passwortantwort war falsch' return render_template('pw_failed.html', msg=msg, site=site) msg = 'No account found!' return render_template('pw_failed.html', msg=msg, site=site) else: return render_template('pw_failed.html')
def post(self, req, **kwargs): user_login = UserLoginSerializer(data=req.data) if user_login.is_valid(): user = User.objects.filter(email=user_login.data['email'], activate=True) if len(user)>0: # используется для рассшифровки хэшированного пароля if compare_hash(user[0].password, crypt.crypt(str(user_login.data['password']),settings.SECRET_KEY_2)): req.session['auth'] = user[0].id return HttpResponseRedirect('/') return Response({'res':'Проверьте корректность email и пароля'}) else: return Response({'res': 'Проверьте указанные данные'}) else: return Response({'res': 'Не правильно введены данные'})
def handle_login(request, response, login_details): # print("handle_login") username, passwd = login_details["user"], login_details["password"] hashed_passwd = REDIS_OBJ.get(username) if hashed_passwd: hashed_passwd = hashed_passwd.decode() if compare_hash(hashed_passwd, crypt(passwd, hashed_passwd)): redir_path = "user/{}/home.html".format(username).encode() # user_session = Session() # user_session(request, response) # print(redir_path) # server.redirect(request, response, redirected_path, 307) return read_html("static/home.html").replace( b"{redirect}", redir_path) return read_html("static/failed_login.html").replace( b'{reason}', b'wrong credentials')
def checkPasswd(name, plainPW): passwd, email = loadPasswd() nameExists(passwd, name) if passwd[name] == 'REVOKED': userError('This name is banned') hash = crypt(plainPW, passwd[name]) # XXX if not hash: from bcrypt import hashpw as crypt_blowfish hash = crypt_blowfish(plainPW.encode('utf-8'), passwd[name].encode('utf-8')) hash = hash.decode('utf-8') if not compare_hash(passwd[name], hash): userError('Password does not match')
def bruteforce(plik, dlug): base = open(plik, 'r') chars = string.ascii_lowercase posiblekey = product(chars, repeat=dlug) base = base.readlines() for line in base: rec = str.split(line, ':') rec = rec[1].strip() for key in posiblekey: sts = '' for k in key: sts = sts + k if compare_hash(crypt.crypt(sts, rec), rec): print("Password is found ...", sts) break else: sts = ''
def authenticate(identity): """ Authenication callback. """ if identity.site is not None: return None try: password = _config['configured_users']['users'][identity.login] except KeyError: return None else: if compare_hash(password, crypt(identity.key, password)): # The site value will be used during authorization. identity.site = _config['configured_users']['source'] return True return False
def unix_password_cracker(dictwords, passwords, users): i = 0 for password in passwords: pass_found = 0 print "Password Hash: ", password #We know DES algorithm was used based on 13 char output #hashed password has first 2 character of DES as salt salt = password[:2] print "Identified Salt: ", salt #iterate through dictionary words for word in dictwords: hashed = crypt.crypt(word, salt) if compare_hash(password, crypt.crypt(word, salt)): print "Found Plaintext Password for User %s, Password = %s: " % ( users[i], word) pass_found = 1 i += 1 if pass_found == 0: print "No Password Found for User %s" % (users[i]) i += 1 return
def compare_password(password, cryptedpasswd): return compare_hash(crypt.crypt(crypt.crypt(password, cryptedpasswd), cryptedpasswd), cryptedpasswd)
--- name: _passwords_equal description: | Compares a plaintext password with an arbitrary 'crypt(3)' hashed password. Uses <https://docs.python.org/3/library/hmac.html> language: plpython3u returns: boolean parameters: - name: p_password_plaintext type: commons.t_password_plaintext - name: p_password_hash type: commons.t_password --- import crypt from hmac import compare_digest as compare_hash # Giving crypt.crypt the full hash as second argument fixes the use of the # right salt and algorithm. Using compare_hash to avoid timing attacks. return compare_hash(crypt.crypt(p_password_plaintext, p_password_hash), p_password_hash)
mhash = pacote.decode('latin1') chash = crypt.crypt(str(msg_id)+str(seg)+str(nseg)+str(tam)+msg, mhash) # Verifica se eh nova conexao if cliente not in cliente_list: cliente_list[cliente] = {} cliente_list[cliente]['janela'] = {} cliente_list[cliente]['gravar'] = 0 cliente_list[cliente]['gravado'] = [] # Atualiza ultima tentativa de contado do cliente cliente_list[cliente]['tempo'] = time() # Verifica integridade do pacote # print(compare_hash(mhash, chash)) if compare_hash(mhash, chash): # Verifica se a mensagem esta dentro do escopo da janela if msg_id < (cliente_list[cliente]['gravar']+Wrx): # Calcula hash do pacote com a probabilidade de Erro data = str(msg_id)+str(seg)+str(nseg) if ErroMD5(): rhash = crypt.crypt(data+'erro', crypt.METHOD_MD5) print('r errado', msg_id) else: rhash = crypt.crypt(data, crypt.METHOD_MD5) print('r certo', msg_id) # Envia confirmacao confirmacao = pack('L', msg_id) confirmacao += pack('L', seg)
""" """ import crypt from hmac import compare_digest as compare_hash enc = crypt.crypt('pass', "hello") print(enc) dcr = compare_hash(enc, crypt.crypt('pass', enc)) print(dcr)
def check_password(self, password_clear): return compare_hash(crypt.crypt(password_clear, self.password), self.password)
import pwd import crypt import getpass from hmac import compare_digest as compare_hash def login(): username = input('Python login: '******'x' or cryptedpasswd == '*': raise ValueError('no support for shadow passwords') cleartext = getpass.getpass() return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd) else: return True hashed = crypt.crypt(plaintext) if not compare_hash(hashed, crypt.crypt(plaintext, hashed)): raise ValueError("hashed version doesn't validate against original")
def validate(self, secret, _hash, **kwargs): salt = kwargs.get("salt", self.salt_from_hash(_hash)) kwargs['salt'] = salt return compare_hash(self.generate(secret, **kwargs), _hash)