예제 #1
0
def newPasswordToOldPasswordComparison(newPassword, oldPassword, oldPasswords):
#    oldPassword = sys.argv[1]
#    newPassword = sys.argv[2]
    newPassword = newPassword.lower()
    oldPassword = oldPassword.lower()
    newPasswordLetters = collections.Counter(newPassword)
    oldPasswordLetters = collections.Counter(oldPassword)
    intersection = newPasswordLetters & oldPasswordLetters
    root = rootWord(newPassword)
#    print intersection
    count = 0 
    for item in intersection:
        count = count + intersection[item]
    percent = float(count)/len(newPassword)
    print percent
    if (percent > .7):
#        print False
        return [False, "Too similar", root]
    else:
        newPassword = str(newPassword)
        if (compareToOldPasswords(oldPasswords, newPassword)):
            return [False, "Too similar", root]
        if (compareToOldPasswords(oldPasswords, root)):
            return [False, "Too similar", root]
        hashedNewPassword = sha256_crypt.using(rounds=1100).hash(newPassword)
        hashedRootWord = sha256_crypt.using(rounds=1100).using().hash(root)
        return [True, hashedNewPassword, hashedRootWord]
예제 #2
0
def register():
    """
    Defines URL/route for employee registration. Not currently active. 

    :return: html page for registration
    :rtype: flask template
    """
    if request.method == 'POST':
        service = EmployeeService()
        username = request.form['username']
        usernameTaken = service.find_existing_employee(username)
        if usernameTaken is not None:
            flash(f"Username: {username} is already taken. Try again")
            return render_template('register.html')
        else:
            password = request.form['password']
            pwHash = sha256_crypt.using(rounds=1000).hash(password)
            data = {
                'username': username,
                'password': pwHash,
                'fName': request.form['fname'],
                'lNmae': request.form['lname'],
                'email': request.form['email'],
                'role': request.form['role']
            }
            #role must be admin, engineer or manager
            result = service.register_employee(data)
            if result is not None:
                flash("Account created. Please log in.")
                return render_template('login.html')
    return render_template('register.html')
예제 #3
0
파일: app.py 프로젝트: SHinds81/Uni-PyFlask
def signup():
    username = request.form['username']
    password = request.form['password']
    firstname = request.form['firstname']
    lastname = request.form['lastname']
    email = request.form['email']
    usertype = request.form['usertype']
    userstatus = 'active'
    hashedPassword = sha256_crypt.using(rounds = 3000).hash(password)
    data1=json.dumps({"userId": username, "firstName": firstname, "lastName": lastname, "emailId": email, "accountType": usertype, "accountStatus": userstatus})
    data=json.dumps({"passHash": hashedPassword, "userId": username})
    
    response = API.test_client().post(
        '/logins',
        data = data,
        content_type='application/json',
    )

    response = API.test_client().post(
        '/users',
        data = data1,
        content_type='application/json',
    )

    return redirect(url_for('index'))
def registerUser():
    if 'register' in request.form:
        service = UserService()
        username = request.form.get('username')
        pwHash = sha256_crypt.using(rounds=1000).hash(
            request.form.get('password'))
        usernameTaken = service.findExistingUser(username)
        if usernameTaken:
            flash("Username: "******" is already taken - please try again")
            return render_template('register.html')
        else:
            userInfo = {
                'username': username,
                'password': pwHash,
                'fName': request.form.get('fname'),
                'lName': request.form.get('lname'),
                'email': request.form.get('email')
            }
            result = service.registerUser(userInfo)
            if result:
                service.add_activity(username, "register")
                flash("Success: Account created - please log in")
            return render_template('login.html')
    else:
        return render_template('register.html')
예제 #5
0
def register():
    if request.method == 'POST':
        success = ""
        username = request.form['uname'].lower()
        password = request.form['pword']
        twofa = request.form['2fa']

        user = User.query.filter_by(username=username).first()

        if (user is not None):
            success = "failure"
        else:
            password = sha256_crypt.using(rounds=324333).hash(password)
            user = User(username=username, password=password, twofa=twofa)

            db.session.add(user)
            db.session.commit()
            success = "success"

        return render_template("register.html", success=success)

    if request.method == 'GET':
        session.clear()
        success = "Please register to access the site"
        return render_template("register.html", success=success)
def add_user():
    """
    Provides logic (via POST) to retrieve data entered on the add user 
    page. Confirms entered username is unique, and prompts for different
    username if not. Data is then sent to cloud database to create a new 
    record in user table. 

    :return: confirmation message user was added, redirects to main menu
    :rtype: flask template
    """
    service = UserService()
    username = request.form['username']
    usernameTaken = service.findExistingUser(username)
    if usernameTaken is not None:
        flash(f"Username {username} is already taken. Please try again")
        return render_template('addUser.html')
    else:
        password = request.form['password']
        pwHash = sha256_crypt.using(rounds=1000).hash(password)
        data = {
            'username': username,
            'password': pwHash,
            'fName': request.form['fname'],
            'lName': request.form['lname'],
            'email': request.form['email']
        }
        result = service.add_user(data)
        if result is not None:
            flash(f"Success! User {username} created ")
            return render_template('menu.html')
예제 #7
0
def register():
    # Output message if something goes wrong
    msg = ''
    # Check if "username", "password" and "email" POST requests exist (user submitted form)
    if request.method == 'POST':
        # Create variables for easy access
        firstname = request.form['first_name']
        lastname = request.form['last_name']
        email = request.form['email']
        password = request.form['password']
        hashedpassword = sha256_crypt.using(rounds=1000).hash(password)

        # check whether the email has already registered in the database
        account = db.get_an_user(email)

        # If account exists show error and validation checks
        if account:
            msg = 'Account with this email has already existed!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address!'
        elif not firstname or not lastname or not email or not password:
            msg = 'Please fill out the form!'

        # if account doesn't existed, show the successful message and back to the login page
        else:
            db.insert_account(firstname, lastname, email, hashedpassword)
            msg = 'You have successfully registered!'
            return render_template('index.html', msg=msg)

    # Show registration form with message (if any)
    return render_template('register.html', msg=msg)
예제 #8
0
파일: app.py 프로젝트: CeciliaCY/AppDocker
def register():
    if request.method =='POST':
        result = ""
        #Using lower() to avoid case sensetive for user name
        username = request.form['uname'].lower()
        pwordInput = request.form['pword']
        fa = request.form['2fa']

        user = User.query.filter_by(username=username).first()

        #Validate the inputs
        #if (re.match (r"^([A-Za-z0-9_]){3,20}$",username) and re.match(r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$",pwordInput) and (True if (fa =="") else re.match(r"^\d{11}",fa))):
        #if (re.match (r"^([A-Za-z0-9_]){3,20}$",username) and re.match(r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$",pwordInput) and (True if (fa =="") else re.match(r"^\d{11}",fa))):
            #If user existed, then return failure
        if (user is not None):
            result = "failure"
        else: 
            #Hash password by sha256
            password = sha256_crypt.using(rounds=324333).hash(pwordInput)
            
            #Save password into a dictionary and then save in a file
            user = User(username=username,password=password,twofa = fa)
            db.session.add(user)
            db.session.commit()
            result = "success"
        #else:
            #result = "Username, password or 2FA format doesn't meet the requirement."

        return render_template ('register.html', result = result)

    if request.method == 'GET':
        session.clear()
        return render_template ('register.html')
예제 #9
0
파일: api.py 프로젝트: PIOT2020/PartA
def encrypt(password):
    """Used for encrypting paswords before storing them to the database."""
    hashedPassword = sha256_crypt.using(salt="salting").hash(password)
    print(hashedPassword)
    hashedPassword = hashedPassword[:-4]
    print(hashedPassword)
    return hashedPassword
def update_user(username):
    """
    Provides logic to retrieve edited details from update user form, and
    then insert in database. If password is changed, hashes password
    and stores hash. Redirects to list of users after update. 

    :param username: username=primary key for user in user table
    :type username: string
    :return: Confirmation message, redirects to user view/search page.
    :rtype: flask template
    """
    #get current user details in order to retain password if needed
    service = UserService()
    data = {
        'fName': request.form['fname'],
        'lName': request.form['lname'],
        'email': request.form['email']
    }
    if request.form["password"] != "":
        data["password"] = sha256_crypt.using(rounds=1000).hash(
            request.form["password"])
    # call user service to send new user value
    service.update_user(username, data)
    flash(f"successfully updated user: {username}")
    return redirect(url_for("users.list_users"))
예제 #11
0
def SetPassword(request):
    if request.method == 'POST':
        data = request.POST
        hash = sha256_crypt.using(rounds=5000).hash(data['password'])
        if Registro.objects.filter(email=data['email']):
            Registro.objects.select_for_update().filter(
                email=data['email']).update(pswd=hash)
    return JsonResponse({'Success': '200'})
예제 #12
0
    def hash_card(self, card_id):
        """create a hash of input card_id

        Returns:
            (string): Returns hashed string.
        """
        hash = sha256_crypt.using(salt_size=0, rounds=53500).hash(str(card_id))
        return hash[-86:]
예제 #13
0
 def check_password(self, password):
     """
     Check if the password for a user is correct
     """
     check_hash = sha256_crypt.using(salt_size=16,
                                     salt=self.salt).hash(password)
     print("Password Provided:", check_hash)
     print("Actual Password:", self.hash)
     if check_hash == self.hash:
         return True
     else:
         return False
예제 #14
0
def SignUp(request):
    if request.method == 'POST':
        data = request.POST
        users = Registro.objects.filter(email=data['email'])
        if users:
            return HttpResponseNotFound("Email already in use.")
        newcode = 1234
        hash = sha256_crypt.using(rounds=5000).hash(data['password'])
        newuser = Registro.objects.create(nombre=data['name'],
                                          email=data['email'],
                                          password=newcode,
                                          pswd=hash)
        return JsonResponse({'Status': 'Succesfully registered!'})
예제 #15
0
 def _get_password_script(self):
     #
     # BUG: hash should be hash_str, you can not use hash and .hash as function
     #
     script = []
     if not self.password:
         return ""
     # repeatable salt if needed for testing
     # hash = sha256_crypt.using(salt='qY2oeR.YpL', rounds=5000).hash(
     # self.password)
     hash = sha256_crypt.using(rounds=5000).hash(self.password)
     script.append(f'echo "$FIRSTUSER:"\'{hash}\' | chpasswd -e')
     return '\n'.join(script)
def similar(newPassword, oldPasswords):

#set old passwords to input
    similarityDifficulty = 4
    numMaxCheck = 0
    generatedPasswords = []

    #process input args
    root = (rootWord(newPassword)) 
        

    if(similarityDifficulty == 4):
        numMaxCheck = 12
        #create a list of all mangled passwords 
        #mangle password based on rules above common rules can be combined
        generatedPasswords.append( (newPassword) )
        generatedPasswords.append( (root ) )
        generatedPasswords.extend( duplicateFront(newPassword))
        generatedPasswords.extend( deleteFirstSpecialChar(newPassword))
        generatedPasswords.extend( addSpecialCharacterToFront(newPassword))
        generatedPasswords.extend( deleteLastSpecialChar(newPassword))
        generatedPasswords.extend( addSpecialCharacterToEnd(newPassword))
        generatedPasswords.extend( deleteBack(newPassword))
        generatedPasswords.extend( deleteFront(newPassword))
        generatedPasswords.extend( duplicateBack(newPassword))
        generatedPasswords.extend( duplicateFront(newPassword))
        generatedPasswords.extend( rotationLeft(newPassword, 5))
        generatedPasswords.extend( rotationRight(newPassword, 5))
        generatedPasswords.extend( allPossibleNumberChanges(newPassword, True, numMaxCheck))
        generatedPasswords.extend( capitalizeALetter(newPassword, True, 5))
        generatedPasswords.extend( lowercaseALetter(newPassword, True, 5))
    elif (similarityDifficulty == 3):
        print "Different Similarity levels"

    elif (similarityDifficulty == 2):
        print "Depending on rule decisions"

    else: #must be (similarityDifficulty == 1):
        print "Up to the admin to decide what they want"
    print generatedPasswords
    #check if the any of the mangled passwords match the old passwords
    for password in generatedPasswords:
        if (compareToOldPasswords(oldPasswords, str(password))):
            return [False, "Too similar", root]
    #one way hash the password
    hashedNewPassword = sha256_crypt.using(rounds=1100).hash(newPassword)
#hashedRootWord = sha256_crypt.using(rounds=1100).using().hash(root)
    #print (True, hashedNewPassword, hashedRootWord, NewPassword, hashedRootWord)
    return [True, hashedNewPassword, root]
예제 #17
0
 def new_member(cls, email, password, first_name, last_name):
     """
     Add a new member
     """
     salt = secrets.token_hex(8)
     hash = str(sha256_crypt.using(salt=salt, relaxed=True).hash(password))
     print(password, hash)
     u = cls(email=email,
             hash=hash,
             salt=salt,
             first_name=first_name,
             last_name=last_name)
     db.session.add(u)
     db.session.commit()
     return u
예제 #18
0
파일: logbook.py 프로젝트: eddybl/py_elog
def _handle_pswd(password, encrypt=True):
    """
    Takes password string and returns password as needed by elog. If encrypt=True then password will be
    sha256 encrypted (salt='', rounds=5000). Before returning password, any trailing $5$$ will be removed
    independent off encrypt flag.

    :param password: password string
    :param encrypt: encrypt password?
    :return: elog prepared password
    """
    if encrypt and password:
        from passlib.hash import sha256_crypt
        return sha256_crypt.using(salt='', rounds=5000).hash(password)[4:]
    elif password and password.startswith('$5$$'):
        return password[4:]
    else:
        return password
    def is_authorized(self):
        header = flask.request.headers.get('Authorization', None)
        if not header:
            return False
        username_password = base64.b64decode(header.split('Basic ')[1])
        username_password_utf8 = username_password.decode('utf-8')
        username, password = username_password_utf8.split(':')
        if (self._pw_aux == password):
            passwordhash = self._pwhash
        else:
            passwordhash = sha256_crypt.using(
                salt=self._sha256salt).hash(password)
            self._pw_aux = password
            self._pwhash = passwordhash
        for pair in self._username_pwhash_list:
            if pair[0] == username and pair[1] == passwordhash:
                self._username = username
                return True

        return False
예제 #20
0
def crackPass(fullHash, algo, salt, wordList):
    dictFile = open(wordList, 'r')

    for word in dictFile.readlines():
        word = word.strip('\n')
        if algo == hashTypes['MD5']:
            if md5_crypt.using(salt=salt, rounds=5000).verify(word, fullHash):
                print("[+] Found Password: "******"\n")
                return
        if algo == hashTypes['SHA-256']:
            if sha256_crypt.using(salt=salt,
                                  rounds=5000).verify(word, fullHash):
                print("[+] Found Password: "******"\n")
                return
        if algo == hashTypes['SHA-512']:
            if sha512_crypt.using(salt=salt,
                                  rounds=5000).verify(word, fullHash):
                print("[+] Found Password: "******"\n")
                return
    print("[-] Password Not Found.\n")
    return
예제 #21
0
파일: app.py 프로젝트: SHinds81/Uni-PyFlask
def login():
   if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        hashedPassword = sha256_crypt.using(rounds = 3000).hash(password)
        response = API.test_client().get(
            '/logins/' + username, 
            content_type='application/json',
        )

        response1 = API.test_client().get(
            'users/' + username,
            content_type='application/json',
        )

        data2 = json.loads(response.get_data(as_text=True))
        data3 = json.loads(response1.get_data(as_text=True))

        userId = data2["loginDetails"]["userId"]
        passHash = data2["loginDetails"]["passHash"]
        userType = data3["userDetails"]["accountType"]

        try:
        
            if str(userType) == 'admin':
                if str(userId) == username or str(hashedPassword) == passHash:
                    if(sha256_crypt.verify(password, passHash)):
                        return render_template('adminView.html', value = username)
                flash('Invalid Login Credentials!')

            elif str(userType) != 'admin':
                if str(userId) == username or str(hashedPassword) == passHash:
                    if(sha256_crypt.verify(password, passHash)):
                        return render_template('view.html', value = username)
                flash('Invalid Login Credentials!')
            
        except:
            flash('Invalid Login Credentials!')

        return redirect(url_for('index'))
예제 #22
0
파일: views.py 프로젝트: vivek0079/CodePro
def registerUser(request):
    if request.is_ajax():
        username = request.POST.get('username')
        password = request.POST.get('password')
        password = sha256_crypt.using(rounds=20000).hash(password)
        email = request.POST.get('email')
        status = 0
        if User.objects.filter(username__iexact=username).exists():
            status = 404
        else:
            new_user = User.objects.create(username=username,
                                           password=password,
                                           email=email)
            new_user.save()
            request.session['username'] = username
            status = 200
        res = {
            "status": status,
        }
        return JsonResponse(res, safe=False)
    else:
        return HttpResponseBadRequest()
예제 #23
0
    qresult = db.Column(db.String(3000), nullable=False)
    username = db.Column(db.String(20), nullable=False)

    def __repr__(self):
        return "<QueryHistory %r %r %r %r>" % (self.qid, self.qtext,
                                               self.qresult, self.username)


#Create DB
db.create_all()

#Admin: expected account details - filter
if (User.query.filter_by(username="******").count() == 0):
    admin_account = User(
        username="******",
        password=sha256_crypt.using(rounds=324333).hash("Administrator@1"),
        twofa="12345678901",
        role="admin")
    db.session.add(admin_account)
    db.session.commit()


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        success = ""
예제 #24
0
#different methods (you only have to give the
#first six hex characters for the hash):MD5, SHA-1, SHA-256, SHA-512, DES
#MD5 SHA1 SHA256 SHA512 DES
#Also note the number hex characters that the hashed value uses:MD5, Sun MD5, SHA-1, SHA-256, SHA-512
#############
from passlib.hash import md5_crypt, sun_md5_crypt, sha1_crypt, sha256_crypt, sha512_crypt, des_crypt
words = ["hello"]
salt = "ZDzPE45C"

for x in words:
    print("Hashes for \"" + x + "\":")
    md5 = md5_crypt.using(salt=salt).hash(x)
    print("MD5: " + md5)
    sha1 = sha1_crypt.using(salt=salt).hash(
        x)  # .encrypt deprecatyed, using hash instead
    print("SHA1: " + sha1)
    sha256 = sha256_crypt.using(salt=salt).hash(x)
    print("SHA256: " + sha256)
    sha512 = sha512_crypt.using(salt=salt).hash(x)
    print("SHA512: " + sha512_crypt.using(salt=salt).hash(x))

    des = des_crypt.using(salt=salt[:2]).hash(x)  # first 2 chars of salt
    print("DES: " + des)
    print("")
    print("Hex length for \"" + x + "\":")
    print("MD5: " + str(len(md5)))
    print("Sun MD5: " + str(len(sun_md5_crypt.using(salt=salt).hash(x))))
    print("SHA-1: " + str(len(sha1)))
    print("SHA-256: " + str(len(sha256)))
    print("SHA=512: " + str(len(sha512)))
예제 #25
0
from passlib.hash import sha256_crypt
import dc_classifer as dc
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)


@app.before_first_request
def before_req():
    dc.intialize()


api = Api(app)

hash1 = sha256_crypt.using(rounds=40000).hash("Shankar123@")
hash2 = sha256_crypt.using(rounds=40000).hash("HeavyWater123@")


class HelloWorld(Resource):
    def get(self):
        headers = {'Content-Type': 'text/html'}
        return make_response(render_template('index.html'), 200, headers)


parser = reqparse.RequestParser()
parser.add_argument('inp_str')
parser.add_argument('passw')
parser.add_argument('userName')

예제 #26
0
    def create_account_table(self):
        with self.connection.cursor() as cursor:
            cursor.execute("DROP TABLE IF EXISTS customers")
            cursor.execute("DROP TABLE IF EXISTS cars_list")
            cursor.execute("DROP TABLE IF EXISTS bookings")

            # Creating default password and converting to hashing
            hashedpassword = sha256_crypt.using(rounds=1000).hash("123")

            cursor.execute("""
                CREATE TABLE IF NOT EXISTS `customers` (
                    `customer_id` int(11) NOT NULL AUTO_INCREMENT,
                    `first_name` varchar(100) NOT NULL,
                    `last_name` varchar(100) NOT NULL,
                    `email` varchar(100) NOT NULL,
                    `password` text NOT NULL,
                    PRIMARY KEY (`customer_id`),
                    UNIQUE(`email`),
                    KEY `id` (`customer_id`)
                ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
            """)
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'Wayne', 'Wayne', '*****@*****.**', '"
                + hashedpassword + "')")
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'John', 'Mathew', '*****@*****.**', '"
                + hashedpassword + "')")
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'Anna', 'Williams', '*****@*****.**', '"
                + hashedpassword + "')")
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'Harry', 'Robert', '*****@*****.**', '"
                + hashedpassword + "')")
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'Charlie', 'William', '*****@*****.**', '"
                + hashedpassword + "')")
            cursor.execute(
                "INSERT IGNORE INTO `customers` VALUES (NULL, 'Oliver', 'Michelle', '*****@*****.**', '"
                + hashedpassword + "')")

            cursor.execute("""
                CREATE TABLE IF NOT EXISTS `cars_list` (
                    `car_id` int(15) NOT NULL AUTO_INCREMENT,
                    `make_name` varchar(100) NOT NULL,
                    `model_name` varchar(100) DEFAULT NULL,
                    `seating_capacity` varchar(1) DEFAULT NULL,
                    `colour` varchar(20) DEFAULT NULL,
                    `car_type` varchar(20) DEFAULT NULL COMMENT '1:Sedan | 2:Hatch | 3:SUV',
                    `price_per_hour` decimal(10,2) NOT NULL,
                    `registration_no` varchar(10) DEFAULT NULL,
                    `status` varchar(15) NOT NULL,
                    `latitude` varchar(20)  NOT NULL,
                    `longitude` varchar(20) NOT NULL,
                    UNIQUE(`registration_no`),
                    PRIMARY KEY (`car_id`)                    
                ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
            """)
            cursor.execute(
                "INSERT IGNORE INTO `cars_list` VALUES (NULL, 'Toyota', 'Camry', '4', 'Red', 'Sedan', 15, "
                "'Flinders', 'available' , -35.8183, 146.9671);")
            cursor.execute(
                "INSERT IGNORE INTO `cars_list` VALUES (NULL, 'Mazda', 'CX-5', '4', 'Yellow', 'SUV', 20, "
                "'Box hills', 'available', -37.8181, 145.1239);")
            cursor.execute(
                "INSERT IGNORE INTO `cars_list` VALUES (NULL, 'Nissan', 'Altima', '5', 'Black', 'Sedan', 10, "
                "'North Melbourne', 'available', -37.7992, 144.9467);")

            cursor.execute("""
                CREATE TABLE IF NOT EXISTS `bookings` (
                    `booking_id` int(11) NOT NULL AUTO_INCREMENT,
                    `customer_id` int(11) NOT NULL,
                    `car_id` int(11) NOT NULL,
                    `pickup_date` DATE NOT NULL,
                    `pickup_time` varchar(30) NOT NULL,
                    `return_date` DATE NOT NULL,
                    `return_time` varchar(30) NOT NULL,
                    `booking_amount` decimal(10,2) NOT NULL,
                    `booking_status` varchar(30) NOT NULL,
                    `canceled_date_time` timestamp NULL DEFAULT NULL,
                    PRIMARY KEY (`booking_id`)                  
                ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
            """)

        self.connection.commit()
예제 #27
0
def user_from_key_cached(key):
    key_enc = sha256.using(rounds=5000, salt=salt).hash("bugs")
    return users.get(key_enc)
예제 #28
0
from passlib.hash import sha256_crypt as sha256
import timeit
from functools import lru_cache


salt = "Qazwsx123fjhvnn"


users = {
        sha256.using(rounds=5000).hash("bugs"): "bunny",
        sha256.using(rounds=5000).hash("duffy"): "duck",
        sha256.using(rounds=5000).hash("elmer"): "cat"
        }


def user_from_key(key):
    key_enc = sha256.using(rounds=5000, salt=salt).hash("bugs")
    return users.get(key_enc)


@lru_cache(maxsize=1024)
def user_from_key_cached(key):
    key_enc = sha256.using(rounds=5000, salt=salt).hash("bugs")
    return users.get(key_enc)


# TODO: Add joblib example
def test_crypt():
    print("Crypt without cache: {0}".format(
        timeit.timeit("user_from_key('bugs')",
                      "from __main__ import user_from_key, salt",
예제 #29
0
 def _encrypt(self, clearvalue, salt=None):
     rounds = param_tools.get_global_parameter("rounds_number")
     sha256_crypt.using(rounds=rounds)
     return sha256_crypt.hash(clearvalue)
예제 #30
0
def hashed_token(token: str) -> bytes:
    return sha256_crypt.using(rounds=1000).hash(token)
def hashPassword(password):
    hashedPassword = sha256_crypt.using(rounds = 1100).hash(password)
    return hashedPassword