Example #1
1
def hash_password(password: str) -> Any:
    ph = PasswordHasher()
    try:
        return ph.hash(password)
    except HashingError as e:
        print("ERROR::", e)
        return None
Example #2
0
def verify_password(password: str, hashed_password: str) -> bool:
    ph = PasswordHasher()
    try:
        ph.verify(hashed_password, password)
        return True
    except VerifyMismatchError:
        return False
Example #3
0
    def get_credentials(self, client, login, passwd):
        import argon2
        from argon2 import PasswordHasher

        #         returncode, data = self.get_user_phash(login)
        #         if returncode != 0:
        #             raise ValueError(data)

        #         ph = PasswordHasher()
        # #         print("DATA iS ", data[0])

        #         if ph.verify(data[0], passwd):
        #             self.verified_connections.add((id(client), client.getpeername()))
        #             return [0, "=>Verification successfull."]
        #         else:
        #             raise ValueError("Verification faild")

        response = self.get_user_phash(login)

        if response['returncode'] != 0:
            return self.prepare_response(1, response['data'], "err")

        ph = PasswordHasher()
        try:
            ph.verify(response['data'], passwd)
            self.verified_connections.add((id(client), client.getpeername()))
            answer = "=>Verification successfull."
            return self.prepare_response(0, answer, "answer")

        except argon2.exceptions.VerifyMismatchError as e:
            print("!=> ", traceback.format_exc())
            return self.prepare_response(1, str(e), "err")
Example #4
0
    def get_transactions(self, user_hash: str = ''):
        user_transactions = []
        ph = PasswordHasher()
        if user_hash != '':
            for block in self.chain:
                for transaction in block['transactions']:
                    try:
                        if ph.verify(transaction['sender'], user_hash):
                            temp_transaction = deepcopy(transaction)
                            temp_transaction['sender'] = 'self'
                            user_transactions.append(temp_transaction)
                    except Exception:
                        try:
                            if ph.verify(transaction['reciever'], user_hash):
                                temp_transaction = deepcopy(transaction)
                                temp_transaction['recipient'] = 'self'
                                user_transactions.append(temp_transaction)
                        except Exception:
                            continue
            return user_transactions

        for block in self.chain:
            for transaction in block['transactions']:
                user_transactions.append(transaction)
        return user_transactions
Example #5
0
    def post(self):
        required_fields = ["username", "password", "isAdmin"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        if session.query(User).filter_by(
                username=json_data["username"]).first():
            return jsonify({"success": -1, "error": "User already registered"})
        # hash password
        ph = PasswordHasher()
        hash = ph.hash(json_data["password"])

        try:
            new_user = User(username=json_data["username"],
                            password=hash,
                            admin=json_data["isAdmin"])

            session.add(new_user)
            session.commit()
            return jsonify({"success": 1})
        except:
            return jsonify({
                "success": -1,
                "error": "Error adding new user to db"
            })
Example #6
0
 def _verify_password(self, stored, password):
     ph = PasswordHasher()
     try:
         ph.verify(stored, password)
         return True
     except (exceptions.VerifyMismatchError, exceptions.VerificationError):
         return False
Example #7
0
def login(request):
    if request.session.get('is_login', None):
        return redirect('search_view')

    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "Please check all fields"
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = models.User.objects.get(name=username)
                if not user.has_confirmed:  #Check if the email is verified or not.
                    message = "This account currently is disabled, please check your email."
                    return render(request, 'login/login.html', locals())

                ph = PasswordHasher()
                if ph.verify(user.password, password):
                    #Check if the password is correct, thows exception if it is not
                    #Write user status and data into Session dict
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    request.session['user_email'] = user.email
                    request.session['user_password'] = user.password
                    request.session['user_phone'] = user.phone
                    return redirect('search_view')
            except:
                message = "Username or password is incorrect"
        return render(request, 'login/login.html', locals())

    login_form = UserForm()
    return render(request, 'login/login.html', locals())
Example #8
0
 def verificar_senha(self, password):
     ph = PasswordHasher()
     try:
         ph.verify(self.password, password)
         return {'status': True, 'msg': 'senha correta'}
     except Exception:
         return {'status': False, 'msg': 'senha incorreta'}
Example #9
0
def check_argon(uid, user_lst_3, password_1):
    ph = PasswordHasher()
    try:
        ph.verify(user_lst_3[uid], password_1)
        return True
    except argon2.exceptions.VerifyMismatchError:
        return False
Example #10
0
 def __init__(self, auth_database: Union[str, Path]):
     if isinstance(auth_database, str):
         self.auth_db = Path(auth_database)
     elif isinstance(auth_database, Path):
         self.auth_db = auth_database
     self.ph = PasswordHasher()
     self.logger = logging.getLogger("ModernRelay.log")
def registration(useremail, password):
    try:
        ph = PasswordHasher()
        conn = psycopg2.connect(database=conn_db,
                                user=conn_username,
                                password=conn_password,
                                host=conn_host,
                                port=conn_port)
        cur = conn.cursor()
        cur.execute(
            "SELECT username from forumuser WHERE forumuser.username = "******"'" + useremail + "'")
        conn.commit()  #is there for the sql injecton
        rows = cur.fetchall()
        if (len(rows) >= 1):
            return "This email already exists"
        else:
            randuserid = str(uuid.uuid1())
            print("The password is: " + password)
            pwhash = ph.hash(password)
            cur.execute(
                "INSERT into forumuser(randuserid, username, passwordhash) VALUES(%s,%s,%s)",
                (randuserid, useremail, pwhash))
            conn.commit()
            conn.close()
            return "Registration successful"
    except psycopg2.OperationalError as e:
        return "An Error occured during the registration\n{0}".format(e)
Example #12
0
def signup():
    form = Signup(prefix="a")
    print("hi")
    if request.method == "POST":
        psswd = form.password.data
        psswd_confirm = form.confirm.data
        if psswd != psswd_confirm:
            flash(
                "Input for Password and Confirm Password field doesn't match")
            return redirect(url_for("signup"))
        existing_name = user.query.filter_by(name=form.username.data).first()
        existing_email = user.query.filter_by(email=form.email.data).first()
        if existing_name or existing_email:
            print("This is bad news")
            flash("The email or username are already created")

        else:
            print("hi")
            ph = PasswordHasher()
            name = form.username.data
            email = form.email.data
            hashed_pw = ph.hash(form.password.data)

            usr = user(name=name, email=email, password=hashed_pw)

            db.session.add(usr)
            print(usr)
            db.session.commit()

            print("Saved")
            flash('Thanks for registering')
            return redirect(url_for("home"))

    return render_template("signup.html", form=form)
Example #13
0
 def signin(user):
     __password = user['password']
     try:
         __id = user['id']
         users = User.objects.filter(id=__id)
     except:
         try:
             __email = user['email']
             users = User.objects.filter(email=__email)
         except:
             pass
     ph = PasswordHasher()
     for u in users:
         if (u.active == 'false'):
             return None
         try:
             ph.verify(u.password, __password)
             __logged_user = {
                 'id': u.id,
                 'name': u.name,
                 'email': u.email,
                 'level': u.level
             }
             return __logged_user
         except:
             return None
Example #14
0
def isVerified(password):  #?????
    ph = PasswordHasher()
    hash = ph.hash("")  #password
    if ph.verify(hash, "") == True:
        pass
    else:
        pass
Example #15
0
def new_transaction_screen():
    form = NewTransactionForm()
    if request.method == 'POST':
        from blockchain.api.models import User, Notifications
        reciever_hash = request.form['reciever']
        token = request.form['token']
        ph = PasswordHasher()
        user_hash = ph.hash(current_user.address)
        index = blockchain.new_transaction(current_user.address, user_hash,
                                           reciever_hash, token)
        no1 = Notifications(
            user_address_hash=user_hash,
            time=str(datetime.datetime.now().strftime("%d/%m/%y %I:%M%p")),
            headline='Property Sent',
            text=token,
            read=False)
        no2 = Notifications(
            user_address_hash=reciever_hash,
            time=str(datetime.datetime.now().strftime("%d/%m/%y %I:%M%p")),
            headline='Property Recieved',
            text=token,
            read=False)
        # TODO: if exists in db then update row to match name and details
        db.session.add(no1)
        db.session.add(no2)
        db.session.commit()
        response = {
            'message': 'Transaction will be added to Block {}'.format({index})
        }
        return render_template("message.html", message=response)
    return render_template('new_transaction.html',
                           title='New Transaction',
                           form=form)
Example #16
0
 def verify_password(self, password):
     hasher = PasswordHasher()
     try:
         hasher.verify(self.password_hash, password)
         return True
     except Exception:
         return False
Example #17
0
def createUser():
    data = request.json
    username = data['username']
    password = data['password']
    #Initialise password hasher
    password_hasher = PasswordHasher()
    #Hash the password and get a string of hash.
    password_hash = password_hasher.hash(password)
    #Get database connection
    db = get_db()
    cur = db.cursor()
    #Check if the username is taken
    cur.execute('SELECT * FROM Users WHERE userName=?', (username, ))
    out = {}
    rows = cur.fetchall()
    if len(rows) != 0:
        out['status'] = 'fail'
        out['reason'] = 'Username already taken'
        return jsonify(out)
    else:
        #Store username and password hash in database
        cur.execute('INSERT INTO Users(userName, userPassword) VALUES (?, ?)',
                    (username, password_hash))
        db.commit()
        userId = cur.lastrowid
        #Return userID and userName in response
        out['status'] = 'success'
        out['userId'] = userId
        out['userName'] = username
        return jsonify(out)
Example #18
0
def login():
    message = ""
    site_login = request.form.get("site_login")
    password = request.form.get("password")
    result = db.execute(
        "SELECT password,visible_name,user_id FROM users WHERE login=:login", {
            "login": site_login
        }).fetchone()
    ### users table schema
    ###  user_id | login | password | visible_name
    if result is None:
        message = "Login or password is incorrect. Please try again."
        return render_template("index.html", message=message)

    password_hash = result[0]
    message = password_hash
    visible_name = result[1]
    user_id = result[2]
    try:
        pwd_hasher = PasswordHasher()
        pwd_hasher.verify(password_hash, password)
    except argon2.exceptions.VerifyMismatchError:
        message = "Login or password is incorrect. Please try again."
        return render_template("index.html", message=message)
    except:
        message = "An error has occured during authentication. Please try again."
        return render_template("index.html", message=message)
    session['site_login'] = site_login
    session['visible_name'] = visible_name
    session['user_id'] = user_id
    return redirect(url_for('homepage'))
    def test_check_needs_rehash_no(self):
        """
        Return False if the hash has the correct parameters.
        """
        ph = PasswordHasher(1, 8, 1, 16, 16)

        assert not ph.check_needs_rehash(ph.hash("foo"))
    def test_hash_verify(self, password):
        """
        Hashes are valid and can be verified.
        """
        ph = PasswordHasher()

        assert ph.verify(ph.hash(password), password) is True
Example #21
0
def createAccount():#create account sequence
    try:
        usr = sys.argv[2]
    except:
        print('Usage: ./pythenticator < -c | -l > username')
        exit(0)
    print('Creating user: '******':')
            if u == usr:
                print('user already exists')
                exit(0)
    pw = getpass.getpass(prompt='Enter password for user {}:'.format(usr))#password prompt
    if not policy.test(pw):#policy.test() returns empty list if it passes
        ph = PasswordHasher()
        pwhash = ph.hash(pw)
        with open("users.db", "a") as file:
            file.write(usr)
            file.write(':')
            file.write(pwhash)
            file.write('\n')
            print('User creation successful')
    else:
        print('The password you entered does not meet the following requriements: ', policy.test(pw))
Example #22
0
def authenticate():
    if request.method == 'POST':
        username = request.get_json().get('username')
        password = request.get_json().get('password')

        hash = False
        ph = PasswordHasher()
        session = generateSession()

        for fld_password, in session.query(User.fld_password).\
                filter(User.fld_username == username):
            hash = fld_password

        if (hash is not False):
            try:
                result = ph.verify(fld_password, password)
                if result:
                    response = jsonify({'message': 'Login Successful'})
                    return make_response(response)
            except Exception as err:
                print(err)
                return make_response(
                    jsonify({'error': 'something bad happened'}))

        return make_response(jsonify({'error': 'something bad happened'}))

    return render_template('account_services/authenticate.html')
Example #23
0
def create_user():
    '''Create a new user from a post request form'''
    ph = PasswordHasher()

    name = request.form.get('name')
    password = request.form.get('password')
    verify_password = request.form.get('verify_password')

    if password != verify_password:
        return render_template('auth/register.html',
                               is_taken=False,
                               is_invalid=True)

    user = User(name=name, password=ph.hash(password))
    db.session.add(user)

    try:
        db.session.commit()
    except IntegrityError:
        # User name already taken
        return render_template('auth/register.html',
                               is_taken=True,
                               is_invalid=False)

    return redirect(url_for('login'))
Example #24
0
 def check_password(self, password):
     ph = PasswordHasher()
     try:
         return ph.verify(self.password_hash, password)
     except Exception:
         return False
     return False
Example #25
0
def check_password_hash(hash: str, password: str) -> bool:
    ph = PasswordHasher()
    try:
        if ph.verify(hash, password):
            return True
    except argon2.exceptions.VerifyMismatchError:
        return False
Example #26
0
 def verify_password(self, password):
     hasher = PasswordHasher()
     try:
         hasher.verify(self.password_hash, password)
         return True
     except Exception:
         return False
Example #27
0
    def test_hash_password(self):
        kdf = PasswordHasher()
        password = '******'

        hash = kdf.hash(password)

        self.assertTrue(kdf.verify(hash, password))
Example #28
0
def test_server_authenticate(database, tracer):
    password = "******"
    ph = PasswordHasher()
    password_hash = ph.hash(password)
    user = UserFactory.create(password=password_hash)
    assert database.query(User).one()

    user_store = UserDataStore(database, tracer)
    user_case = UserUseCase(user_store, tracer)

    order_store = OrderDataStore(database, tracer)
    order_case = OrderUseCase(order_store, tracer)

    date = datetime.date.today()
    holiday_store = HolidayDataStore(date, tracer)
    holiday_case = HolidayUseCase(holiday_store, tracer)

    balance_client = BalanceClient(settings.BALANCE_TOKEN)
    balance_case = BalanceUseCase(order_case, balance_client, tracer)

    authentication_case = AuthenticationUseCase(user_case, tracer)

    case = PromotionUseCase(discounts=[holiday_case, user_case], tracer=tracer)

    servicer = PromotionServicer(case, user_case, order_case, balance_case,
                                 authentication_case, tracer)

    request = AuthenticateRequest(email=user.email, password=password)
    result = servicer.Authenticate(request, None)

    assert result.id_token.startswith('ey')
Example #29
0
def update_user_by_id(id):
    if g.user.id == id:
        user = g.user
    else:
        user = User.query.filter(User.id == id).one_or_none()

    if user is None:
        return error(404)

    body = request.json

    password = body.get("password")
    role = body.get("role")

    if password:
        if len(password) < 8:
            return error(400, type="ShortPassword")

        hasher = PasswordHasher()
        hash = hasher.hash(password)
        user.password_hash = hash

    if role:
        if g.user.role != UserRole.ADMIN:
            return error(401, type="InsufficientPermission")

        if role != "normal" and role != "admin":
            return error(400, message="`role` must be one of {normal, admin}.")

        user.role = UserRole.ADMIN if (role == "admin") else UserRole.NORMAL

    db.session.commit()

    return serialize_user(user)
Example #30
0
 def __init__(self, currentPassword, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.currentPassword = None if currentPassword is None else str(currentPassword) 
     self.addWidgets()
     self.pwdhsr = PasswordHasher()
     self.passwordTimer = QtCore.QTimer(timeout=self.validateCurrentPassword)
     self.passwordTimer.setSingleShot(True)        
Example #31
0
    def encrypting_password(self):
        if not self.password:
            return {'status': False, 'msg': 'password not allow blank'}

        password_hash = PasswordHasher()
        self.password = password_hash.hash(self.password)
        return {'status': True, 'msg': 'senha encripitada'}
Example #32
0
def gen_passwd_hash(pw):
    ph = PasswordHasher(hash_len=hash_length,
                        salt_len=salt_length,
                        encoding=encoding,
                        time_cost=time_cost,
                        memory_cost=memory_cost)
    pwhash = ph.hash(pw)
Example #33
0
    def test_verify(self, password):
        """
        Verification works with unicode and bytes.
        """
        ph = PasswordHasher(1, 8, 1, 16, 16, "latin1")
        hash = (  # handrolled artisanal test vector
            u"$argon2i$m=8,t=1,p=1$"
            u"bL/lLsegFKTuR+5vVyA8tA$VKz5CHavCtFOL1N5TIXWSA"
        )

        assert ph.verify(hash, password)
Example #34
0
    def test_hash(self, password):
        """
        Hashing works with unicode and bytes.  Uses correct parameters.
        """
        ph = PasswordHasher(1, 8, 1, 16, 16, "latin1")

        h = ph.hash(password)

        prefix = u"$argon2i$v=19$m=8,t=1,p=1$"

        assert isinstance(h, six.text_type)
        assert h[:len(prefix)] == prefix
Example #35
0
def new_user():
    userid = request.form.get('userid')
    userpw = request.form.get('userpw')
    if userid and userpw:
        if db.query(User).filter(User.account == userid).first():
            flash('id already exists')
        else:
            ph = PasswordHasher()
            hash = ph.hash(userpw)
            user = User(userid, hash)
            db.add(user)
            db.commit()
            session['username'] = user.account
            flash('welcome to people!')
            return redirect(url_for('home'))
    else:
        flash('account id or password is blank.')
    return redirect(url_for('new_user'))
Example #36
0
def login():
    userid = request.form.get('userid')
    userpw = request.form.get('userpw')
    if userid and userpw:
        user = get_user(userid)
        if user:
            ph = PasswordHasher()
            try:
                ph.verify(user.password, userpw)
            except VerifyMismatchError:
                flash('check account or password')
            else:
                session['username'] = user.account
                flash('welcome back!')
                return redirect(url_for('home'))
        else:
            flash('check account or password')
    else:
        flash('account id or password is blank.')
    return redirect(url_for('login'))
Example #37
0
def argon2_test():
    start = time.time()
    ph = PasswordHasher()
    hash = ph.hash(password)
    hashed = hashlib.sha256(hash).digest()
    end = time.time()
    print "argon2 : ",(end-start)
    start = time.time()
    obj =AES.new(hashed,AES.MODE_CBC, 'This is an IV456')
    ciphertext = obj.encrypt("The answer is no")
    end = time.time()
    print "AES Encrypt: ",(end-start)*1000
    start = time.time()
    obj =AES.new(hashed,AES.MODE_CBC, 'This is an IV456')
    plaintext = obj.decrypt(ciphertext)
    end = time.time()
    print "AES Decrypt: ",(end-start)*1000
    my_plaintext = 0xCCCCAAAA55553333
    start = time.time()
    big_cipher = SimonCipher(0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFF0000, key_size=256, block_size=128)
    simon = big_cipher.encrypt(my_plaintext)
    end = time.time()
    print "Simon Encrypt: ",(end-start)*1000
    start = time.time()
    big_cipher1 = SpeckCipher(0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFF0000, key_size=256, block_size=128)
    speck = big_cipher1.encrypt(my_plaintext)
    end = time.time()
    print "Speck Encrypt: ",(end-start)*1000
    start = time.time()
    big_cipher = SimonCipher(0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFF0000, key_size=256, block_size=128)
    plain = big_cipher.decrypt(simon)
    end = time.time()
    print plain
    print "Simon Decrypt: ",(end-start)*1000
    start = time.time()
    big_cipher1 = SpeckCipher(0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFF0000, key_size=256, block_size=128)
    plain = big_cipher1.decrypt(speck)
    end = time.time()
    print plain
    print "Speck Decrypt: ",(end-start)*1000
Example #38
0
 def password(self, password):
     hasher = PasswordHasher()
     ph = hasher.hash(password)
     self.password_hash = ph
 def hash_password(self, password):
     ph = PasswordHasher()
     self.password_hash = ph.hash(password)
 def verify_password(self, password):
     ph = PasswordHasher()
     return ph.verify(self.password_hash, password)