def check_password(self, password): # hash stored in the database = scrypt hash (88 chars) + salt (88 chars) hash = self.user.password[:88] salt = self.user.password[88:] if isinstance(hash, str): hash = hash.encode('utf-8') return check_password_hash(password, hash, salt, N=16384, r=8, p=1, buflen=64)
def login(self, email=None, password=None): email = email or self.email password = str(password or self.password) user = User.objects(email=email).first() if not user or not check_password_hash(password, user.password, user._salt): return False tok = AccessToken(user=self).generate() return {'access_token': tok.token, 'expires_in': randint(0, 200)}
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: username = request.form['username'] password = request.form['password'] #pw_hash = bcrypt.generate_password_hash(password, 10) #hash = password + app.secret_key #hash = hashlib.sha1(hash.encode()) #password = hash.hexdigest() # Check if account exists using MySQL #connection = mysql.connector.connect(host='localhost', database='pythonlogin', user='******', password='******') cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s', (username)) account = cursor.fetchone() if account: salt = account['salt'] password_hash = account['password'] if check_password_hash(password, password_hash, salt): session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] if 'rememberme' in request.form: # Create hash to store as cookie #hash = account['username'] + request.form['password'] + app.secret_key #hash = hashlib.sha1(hash.encode()) #hash = hash.hexdigest() # Cookie expire in 90days expire_date = datetime.datetime.now() + datetime.timedelta( days=90) resp = make_response('Success', 200) resp.set_cookie('rememberme', hash, expires=expire_date) # Update rememeberme in accounts table to the cookie hash cursor.execute( 'UPDATE accounts SET rememberme = %s WHERE id = %s', (hash, account['id'])) mysql.connection.commit() return resp cursor.close() mysql.connection.close() return 'Success' else: msg = '잘못된 비밀번호' else: msg = '존재하지 않는 아이디' return render_template('login.html', msg=msg)
def check_password(self, pw): pw_bin = pw.encode('utf-8') salt_bin = self.password_salt.encode('ascii') hash_bin = self.password_hash.encode('ascii') return check_password_hash( pw_bin, hash_bin, salt_bin, # same as above N=1 << 14, r=8, p=1, buflen=64)
def jwt_authenticate(email, password): """ helper function to authenticate user if credentials are correct :param email: :param password: :return: """ user = User.query.filter_by(email=email).first() if user is None: return None auth_ok = user.facebook_login_hash == password or check_password_hash( password.encode('utf-8'), user.password.encode('utf-8'), user.salt ) if auth_ok: return user else: return None
def verifyUser(email, password, addToActive=False): # hash the email if email is None: hashed_email = current_user.email else: hashed_email = flask_scrypt.generate_password_hash(email, "") # create user class with information from database userDB = User.query.filter_by(email=hashed_email).first() # if the user doesnt exist in database if userDB is None: return False, None, None # format password from database DBpw = userDB.password.encode('utf-8') # check if the hashed email is the same ass the one in the database, just a double check. # Strictly not nececairy, but just seems logical to do. emailOK = hashed_email.decode('utf-8') == userDB.email.decode( 'utf-8') # boolean to compare with # Verify that the password is correct pwOK = flask_scrypt.check_password_hash(password.encode('utf-8'), DBpw[:88], DBpw[88:176]) # Check if the password is correct and email exists in the database if emailOK and pwOK: # decrypte the users encryption key decryptKey = decrypt(password, userDB.enKey.encode('utf-8'), True) # Decrypt the secret key secret_key = decrypt(decryptKey, userDB.secret.encode('utf-8')) if addToActive: # sync with redis! redis_sync(decryptKey, hashed_email) return True, userDB, secret_key return False, userDB, None
def test_check_password_incorrect(self): incorrect_password = '******' salt = self.salt password_hash = self.password_hash self.assertFalse(check_password_hash(incorrect_password, password_hash, salt))
def test_check_password_correct(self): password = '******' salt = self.salt password_hash = generate_password_hash(password, salt) self.assertTrue(check_password_hash(password, password_hash, salt))
def register(): if RegistrationForm().email: carryOverEmail = RegistrationForm().email.data form = RegistrationForm() form2 = TwoFactorAuthRegForm() # form er den første formen som er på /register, som per nå bare inneholder email, passord og en submit-knapp # form2 er den andre formen du kommer til etter du submitter "form". Denne nye siden vil da inneholde QR-koden # for å legge 2fa-nøkkelen inn i din valgte 2fa app. Denne siden har også et passord felt, 2fa felt (for koden du nå kan generere i appen), # og et "read-only" som inneholder eposten du skrev inn på forrige side. if form.validate_on_submit(): errList = [] getPasswordViolations(errList, form.password.data, form.confirm_password.data, form.email.data) # Is there any error in the generated information if len(errList) == 0: # ─── HASHED EMAIL IS USER ID ───────────────────────────────────── hashed_email = flask_scrypt.generate_password_hash( form.email.data, "") # Key MUST have register keyword appended so as not to mix user keys in redis server registerRedisKey = hashed_email + "register".encode('utf-8') # ─── CHECK IF THE EMAIL EXISTS IN DATABASE OR REDIS ─────────────────────── if User.query.filter_by(email=hashed_email.decode( "utf-8")).first() or redis.get(registerRedisKey): flash("Couldn't continue, due to an error", "error") return render_template("register.html", form=form), disable_caching # ─── IF THE USER DOES NOT EXIST IN THE DATABASE ────────────────── # Create a user dictionairy for redis. userDict = {} # add hashed email as key to cleartext email # This can be directly saved to database later as user email userDict['email'] = hashed_email.decode("utf-8") # We need to temporarily keep the users email in plaintext while in redis userDict["PlainEmail"] = form.email.data # ─── SALT AND HASH PASSWORD ────────────────────────────────────── salt = flask_scrypt.generate_random_salt() # add hashed password to user dictionairy # This can be directly saved to database later userDict['password'] = flask_scrypt.generate_password_hash( form.password.data, salt) + salt # ─── GENERATE USER ENCRYPTION KEY ──────────────────────────────── # generate new encrypted key with users password encryptedKey = encrypt(form.password.data, 'generate', True) # decrypt the key again, serves as a double check deKey = decrypt(form.password.data, encryptedKey, True) # If deKey, explicitly show what you are testing this against none. if deKey is not None: userDict['enKey'] = encryptedKey # encrypt the email and add it to userDict userDict['enEmail'] = encrypt(deKey, form.email.data) # ─── TESTING 2-FACTOR AUTHENTICATION ───────────────────────────────────────────────────# # Lager en relativt simpel secret_key. Har kompatibilitet med Google Authenticator. secret_key = pyotp.random_base32() # denne maa tas vare på til neste side, krypteres med kundes passord userDict['secret'] = encrypt(deKey, secret_key) # Genererer link for kundes qr kode qr_link = pyotp.totp.TOTP(secret_key).provisioning_uri( name=form.email.data, issuer_name="Safecoin.tech") # json generate string from dict overwrite the dict from before userDict = dictToStr(userDict) # Add it to the redis server redis.set(registerRedisKey, userDict) # Set session timeout of user at 600 seconds, 10 minutes redis.expire(registerRedisKey, 600) log_startregister(hashed_email) return render_template( 'TwoFactor.html', form2=form2, qr_link=qr_link ), disable_caching # Vi må dra med inn qr_linken for å generere qr_koden korrekt # ─── DERSOM FEIL VED REGISTEREING ─────────────────────────────────────────────── for err in errList: flash(err, "error") elif form.submit.data and not form2.is_submitted(): flash("Couldn't continue, due to an error", "error") if form2.validate_on_submit(): # Regenerate hashed email from last page hashed_email = flask_scrypt.generate_password_hash(carryOverEmail, "") # Key MUST have register keyword appended so as not to mix user keys in redis server registerRedisKey = hashed_email + "register".encode('utf-8') # retrive information from redis userDict = redis.get(registerRedisKey) # delete user from redis redis.delete(registerRedisKey.decode("utf-8")) # Format back to dictionairy userDict = json.loads(userDict) # Check password correctness pwOK = flask_scrypt.check_password_hash( form2.password_2fa.data.encode('utf-8'), userDict['password'][:88].encode('utf-8'), userDict['password'][88:176].encode('utf-8')) if pwOK: # Decrypt the users decryption key decryptionKey = decrypt(form2.password_2fa.data.encode('utf-8'), userDict['enKey'].encode('utf-8'), True) # Decrypt 2FA key with user decryption key twoFAkey = decrypt(decryptionKey, userDict['secret']) # add key to the Timed One Timed Passwords class so it can verify totp = pyotp.totp.TOTP(twoFAkey) # Hvis brukeren scanner qrkoden (som genereres i html) vil koden som vises i appen deres matche koden til totp.now() if totp.verify(form2.otp.data): # user = User(email=hashed_email.decode("utf-8"), enEmail=mailEncrypted, password=(hashed_pw+salt).decode("utf-8"),enKey=encryptedKey, secret=secret_key) # Create user class user = User() user.email = hashed_email user.enEmail = userDict['enEmail'] user.password = userDict['password'] user.enKey = userDict['enKey'] user.accounts = None user.secret = userDict['secret'] db.session.add(user) db.session.commit() flash( 'Your account has been created! You are now able to log in.', 'success') log_register(True, hashed_email) # ─── ADD ACCOUNT WITH MONEY TO USER ───────────────────────────────────────────── # You start with an account that we add so that we and # Whomever is going to thest our site can work with it addNewAccountToCurUser( password=form2.password_2fa.data, otp='', user=User.query.filter_by(email=hashed_email).first(), money=True, isCurrentUser=False) # ─── ADD ACCOUNT WITH MONEY TO USER ───────────────────────────────────────────── return redirect(url_for('home')) flash("Couldn't register user, due to an error", "error") log_register(False, hashed_email) return render_template("register.html", form=form), disable_caching
def check_password(self, password_hash: bytes): return check_password_hash(password_hash, self.password, self.salt)
def test_check_password_correct_with_none_default_params(self): password = '******' salt = self.salt password_hash = generate_password_hash(password, salt, r=10) self.assertTrue(check_password_hash(password, password_hash, salt, r=10))
def validate_password(user, password): return check_password_hash(password,user['password'],user['salt'], N=cpu_cost, r=memory_cost, buflen = hash_size)
def check_password(self, password): return check_password_hash( password, self.password_hash.encode(), self.salt.encode() )
def verify_password(self, password): return check_password_hash(str(password), str(self.password_hash), str(self.password_salt))
def test_password_fail_with_incorrect_salt(self): password = self.password password_hash = self.password_hash salt = generate_random_salt() self.assertFalse(check_password_hash(password, password_hash, salt))
def test_accept_unicode_str_python2(self): salt = generate_random_salt() password = unicode(self.password) password_hash = generate_password_hash(password, salt) self.assertTrue(check_password_hash(password, password_hash, salt))
def checksum(stream, algorithm='crc32', verify=None, salt=None): ''' Calculates the checksum of the given :param:`stream`. :param stream: The object to hash. :type stream: :class:`bytes` or an iterable containing :class:`bytes` objects. If a string is given, or the iterable contains strings, it or they will be encoded to :class:`bytes` using 'UTF-8' encoding. :param algorithm: Specifies what algorithm should be used to calculate the checksum. Can be 'crc32' or any algorithm supported by :mod:`hashlib`. :type algorithm: :class:`str` :returns: :class:`int` if :param:`algorithm` is 'crc32', otherwise :class:`str` ''' CRC32 = 'crc32' SCRYPT = 'scrypt' BCRYPT = 'bcrypt' is_bytes = hasattr(stream, 'decode') if algorithm == SCRYPT: result = flask_scrypt.gemerate_password_hash(stream, salt) elif algorithm == BCRYPT: result = flask_bcrypt.gemerate_password_hash(stream) elif algorithm == CRC32: if is_bytes: result = zlib.crc32(stream) else: result = 0 for brook in stream: result = zlib.crc32(brook, result) result = result & 0xffffffff else: hasher = hashlib.new(algorithm) if is_bytes: hasher.update(stream) else: for brook in stream: hasher.update(brook) result = hasher.hexdigest() if verify: if algorithm == SCRYPT: returning = flask_scrypt.check_password_hash(stream, verify, salt) elif algorithm == BCRYPT: returning = flask_bcrypt.check_password_hash(verify, stream) else: returning = result == verify else: returning = result return returning
def upload_file(): if request.method == 'POST': # Check whether or not the user is allowed password = request.form.get('password') if not check_password_hash(password, PASSWORD_HASH, SALT): return abort(405) # Get info from the POST request file = request.files['file'] # Use .get('field_name') instead of 'request.form['field_name'] to make it optional: It returns # None instead of KeyError when the field is not sent custom_extension = request.form.get('custom_extension') preserve_filename = request.form.get('preserve_filename') custom_filename = request.form.get('custom_filename') do_not_redirect = request.form.get('do_not_redirect') if file and (allowed_file(file.filename) or custom_extension): if custom_extension in ALLOWED_EXTENSIONS: extension = custom_extension else: if re.search(r'\..', file.filename): extension = file.filename.rsplit('.', 1)[1] # This adds .txt extension to extensionless files else: extension = 'txt' # Either create random name or keep the one sent, after securing it if custom_filename: filename = secure_filename(custom_filename) + "." + extension elif preserve_filename: filename = secure_filename(file.filename) output = (os.path.join(app.config['UPLOAD_FOLDER'], filename)) # If output name already exists, create a temporary file, prepending the random # string and using the original name as a suffix (preceded by an underscore) if os.path.exists(output): output = mkstemp(prefix="", dir=app.config['UPLOAD_FOLDER'], suffix="_" + filename)[1] file.save(output) filename = os.path.basename(output) else: file.save( os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: # Create temp file safely and store its path output = mkstemp(suffix="." + extension, dir=app.config['UPLOAD_FOLDER'], prefix="")[1] filename = os.path.basename(output) file.save(output) # Optimise png, tiff etc, remove metadata from files (images and videos) and compress JPGs postprocess(extension, output) if do_not_redirect: # Return the URL of the uploaded file in plain text # app.logger.info('do_not_redirect is defined') full_url = str(request.base_url) + str(filename) + '' return full_url.strip() else: # If a modern browser should be able to display the file, redirect to it # app.logger.info('do_not_redirect undefined') if extension.lower() in STREAMABLE_EXTENSIONS: return redirect(url_for('download_file', filename=filename)) else: return abort(403) return '''
def check_password(self, ptext): # XXX - There could be issues casting unicode to string here return flask_scrypt.check_password_hash( str(ptext), str(self.passhash), str(self.passsalt))