Exemple #1
1
def hash_password(password: str) -> Any:
    ph = PasswordHasher()
    try:
        return ph.hash(password)
    except HashingError as e:
        print("ERROR::", e)
        return None
Exemple #2
0
def add_property():
    form = PropertyForm()
    if request.method == 'POST':
        name = request.form['property_name']
        details = request.form['property_details']
        property_info = name + details
        ph = PasswordHasher()
        user_hash = ph.hash(current_user.address)
        key = blockchain.add_property(property_info, user_hash)
        from blockchain.api.models import Property, Notifications
        property = Property(token=key, name=name, body=details)
        ph = PasswordHasher()
        user_address_hash = ph.hash(current_user.address)
        no = Notifications(
            user_address_hash=user_address_hash,
            time=str(datetime.datetime.now().strftime("%d/%m/%y %I:%M%p")),
            headline='Property Added',
            text=key,
            read=False)
        # TODO: if exists in db then update row to match name and details
        db.session.add(property)
        db.session.add(no)
        db.session.commit()
        message = "Property added successfully with key:{}".format(key)
        return render_template('message.html', message=message)
    return render_template('new_property.html', form=form)
Exemple #3
0
def setup_function(function):
    db.drop_all_tables(with_all_data=True)
    db.create_tables()

    ph = PasswordHasher()

    with db_session:
        editor = Group(id=3, name="Editor")
        moderator = Group(id=2, name="Moderator")
        admin = Group(id=1, name="Admin")

        User(
            id=1,
            nickname="Leader",
            email="*****@*****.**",
            password=ph.hash("test1"),
            groups=[admin],
        )
        User(
            id=2,
            nickname="Mary",
            email="*****@*****.**",
            password=ph.hash("test2"),
            groups=[moderator],
        )
        User(
            id=3,
            nickname="Jürgen",
            email="*****@*****.**",
            password=ph.hash("test3"),
            groups=[editor],
        )
Exemple #4
0
    def mutate(self, info, email=None, name=None, role=None, get_alerts=None, old_password=None, new_password=None):
        if get_jwt_claims()['role'] == 'Admin' and email and email != get_jwt_identity():
            user = User.query.filter_by(email=email).first()
            if name:
                user.name = name
            if role:
                user.role = role
            if get_alerts is not None:
                user.get_alerts = get_alerts
            if new_password:
                ph = PasswordHasher()
                user.password = ph.hash(new_password)

            db.session.commit()
        else:
            user = User.query.filter_by(email=get_jwt_identity()).first()
            ph = PasswordHasher()
            if name:
                user.name = name
            if get_alerts is not None:
                user.get_alerts = get_alerts
            if old_password and new_password and ph.verify(user.password, old_password):
                user.password = ph.hash(new_password)

            db.session.commit()
        return UpdateUserMutation(user=user)
    def test_type_is_configurable(self):
        """
        Argon2id is default but can be changed.
        """
        ph = PasswordHasher(time_cost=1, memory_cost=64)
        default_hash = ph.hash("foo")

        assert Type.ID is ph.type is ph._parameters.type
        assert Type.ID is extract_parameters(default_hash).type

        ph = PasswordHasher(time_cost=1, memory_cost=64, type=Type.I)

        assert Type.I is ph.type is ph._parameters.type
        assert Type.I is extract_parameters(ph.hash("foo")).type
        assert ph.check_needs_rehash(default_hash)
Exemple #6
0
def isVerified(password):  #?????
    ph = PasswordHasher()
    hash = ph.hash("")  #password
    if ph.verify(hash, "") == True:
        pass
    else:
        pass
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)
    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
Exemple #10
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'))
Exemple #11
0
def main():
    """Testing 'argon2-cffi' package"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbosity",
        dest="verbosity",
        action="count",
        default=0,
        help="set verbosity level",
    )
    args = parser.parse_args()

    if args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    elif args.verbosity > 1:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.ERROR)

    logging.debug(f"{argon2.__name__} {argon2.__version__}")

    ph = PasswordHasher()
    dummy_hash = ph.hash("s3kr3tp4ssw0rd")
    ph.verify(dummy_hash, "s3kr3tp4ssw0rd")
    ph.check_needs_rehash(dummy_hash)
Exemple #12
0
def setup_initial_data(db):
    from argon2 import PasswordHasher

    ph = PasswordHasher()
    u1 = User(name="User 1", password=ph.hash("password1"))
    u2 = User(name="User 2", password=ph.hash("password2"))
    c1 = Client(name="client_u1_1",
                user=u1,
                token="aaaaAAAAbbbbBBBB0000111-C1")
    c2 = Client(name="client_u1_2",
                user=u1,
                token="aaaaAAAAbbbbBBBB0000111-C2")
    a1 = Application(
        registration_id="app_c1_1",
        client=c1,
        routing_token="aaaaAAAAbbbbBBBB0000111-A1",
    )
    a2 = Application(
        registration_id="app_c1_2",
        client=c1,
        routing_token="aaaaAAAAbbbbBBBB0000111-A2",
    )
    m1 = Message(data='{"name":"message1"}',
                 priority=Priority.NORMAL,
                 time_to_live=0,
                 target=a1)
    m2 = Message(data='{"name":"message2"}',
                 priority=Priority.NORMAL,
                 time_to_live=0,
                 target=a1)

    db.session.add_all([u1, u2, c1, c2, a1, a2, m1, m2])
    db.session.commit()
Exemple #13
0
def update_crypto_Argon2_password_only(new_password, salt2,
                                       master_key_encrypted):
    salt1 = random_bytes(16)
    salt2 = random_bytes(16)
    ph = PasswordHasher()
    password_hashed = ph.hash(new_password)
    return 'Argon2', password_hashed, salt1, salt2, master_key_encrypted
Exemple #14
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)
Exemple #15
0
    def hash_sample_id(hasher: argon2.PasswordHasher,
                       sample: Sample,
                       remove_id=False):
        """Produce hash of sample.id.

        Argon2 hash encoding is stored in sample.hash, and the sample.id hash
        itself is stored in sample.hash_id.

        Parameters
        ----------
        hasher : argon2.PasswordHasher
            Instance of `argon2.PasswordHasher`.
        sample : Sample
            Sample object.
        removeID : bool, optional
            Overwrite sample.id with sample.hash_id if True. Default is False.

        Returns
        -------
        None.
        """
        sample.hash = hasher.hash(sample.id)
        sample.hash_id = sample.hash.split("$")[-1]
        if remove_id:
            sample.id = sample.hash_id
Exemple #16
0
 def make_password(self):
     """Generate Argon2 hash of the provided password."""
     # ref: https://argon2-cffi.readthedocs.io/en/stable/api.html
     # Note: Argon2 adds a salt by default.
     ph = PasswordHasher()
     hash = ph.hash(self.password)
     self.password = hash
Exemple #17
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))
Exemple #18
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'}
    def test_hash_password(self):
        kdf = PasswordHasher()
        password = '******'

        hash = kdf.hash(password)

        self.assertTrue(kdf.verify(hash, password))
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)
Exemple #21
0
def login():
    """Retrieve a token"""
    data = request.get_json()
    user = User.query.filter_by(username=data["username"]).first()

    if not user:
        return jsonify({"message": "Invalid credentials"}), 401

    try:
        hasher = PasswordHasher()
        hasher.verify(user.password, data["password"])
    except (VerifyMismatchError, VerificationError, InvalidHash,
            AttributeError):
        # This must also return 401 or else the user may learn
        # private information
        return jsonify({"message": "Invalid credentials"}), 401

    # Rehash password if the parameters of the PasswordHasher change.
    # https://argon2-cffi.readthedocs.io/en/stable/api.html
    if hasher.check_needs_rehash(user.password):
        user.password = hasher.hash(data["password"])
        db.session.add(user)
        db.session.commit()

    access_token = create_access_token(identity=user.username, fresh=True)
    refresh_token = create_refresh_token(user.username)

    return (jsonify({
        "access_token": access_token,
        "refresh_token": refresh_token
    }), 200)
Exemple #22
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)
Exemple #23
0
def _console_test(argv):
    pw = argv[1]
    salt_length = int(argv[2])
    hash_length = int(argv[3])

    print('Password:    %s' % pw)
    print('Salt Length: %s' % salt_length)
    print('Hash Length: %s' % hash_length)
    print('------------------------------')
    print('Calculating hash...')

    ph = PasswordHasher(hash_len=hash_length,
                        salt_len=salt_length,
                        encoding='utf-8',
                        time_cost=1000,
                        memory_cost=1024)
    pwhash = ph.hash(pw)

    print('Verifying hash...')

    ph2 = PasswordHasher()

    verified = ph2.verify(pwhash, pw)

    parsed = parse_argon_hash(pwhash)

    print('Results:')
    print('Hash    : %s' % pwhash)
    print('Verified: %s' % verified)
    print('Parsed  : %s' % parsed)
    """
Exemple #24
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)
Exemple #25
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"
            })
Exemple #26
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')
Exemple #27
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)
    def login(self, username, password):
        success = False
        msg = ''
        userID = 'N/A'
        key = 'N/A'

        self.cursor.execute(
            """select password, id from users
			where username = %s""", (username, ))

        if self.cursor.rowcount == 0:
            success = False
            msg += '\n\tUsername does not exists'

        elif self.cursor.rowcount != 1:
            success = False
            msg += '\n\tUnknown Error'

        else:
            row = self.cursor.fetchone()
            hashed = row[0]
            userID = row[1]

            verifier = PasswordHasher()
            try:
                verifier.verify(hashed, password)
                success = True
            except:
                success = False

            if success:
                msg += 'Authenticated'

                if verifier.check_needs_rehash(hashed):
                    hashed = verifier.hash(password)
                    count = self.cursor.execute(
                        """update users
						set password = %s
						where username = %s""", (hashed, username))

                    if count != 1:
                        msg += 'Failed to rehash password, contact support'
                        logging.error('Failed to rehash password')
                        self.db.rollback()
                    else:
                        self.db.commit()

                self.cursor.execute(
                    """select activationKey from productKey
					where userID = %s""", (userID, ))

                row = self.cursor.fetchone()
                key = row[0]

            else:
                success = False
                msg += 'Incorrect Password'

        return success, msg, userID, key
Exemple #29
0
 def create(self, user_id, birthday, identity, email, name, password):
     """Create an user."""
     with self.tracer.start_as_current_span("UserUseCase.create",
                                            kind=SERVER):
         ph = PasswordHasher()
         password_hash = ph.hash(password)
         return self.store.create(user_id, birthday, identity, email, name,
                                  password_hash)
Exemple #30
0
    def hashedConnections(self):
        pHasher = PasswordHasher()
        hashedArray = []

        for connection in self.connections:
            hashedArray.append(pHasher.hash(connection))

        return hashedArray
    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
Exemple #32
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'))
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
Exemple #34
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)