def change_password(): db_manager = DatabaseManager() username = request.json.get('username') old_password = sha512_crypt.encrypt( request.json.get('old_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) new_password = sha512_crypt.encrypt( request.json.get('new_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) token = request.json.get('token') # Not everything filled in if username == None or old_password == None or new_password == None or token == None: abort(400) # Verifiy token token_credentials = db_manager.verify_auth_token(token=token) if token_credentials is None: abort(401) elif not db_manager.check_password(token_credentials[0], token_credentials[1]): abort(401) elif token_credentials[0] != username: abort(401) if db_manager.check_password(username, old_password): db_manager.change_password(username, old_password, new_password) return response_cache_header("Changed password", cache_control="no-cache") else: return response_cache_header("ERROR, Wrong password", cache_control="no-cache")
def change_password(): db_manager = DatabaseManager() username = request.json.get('username') old_password = sha512_crypt.encrypt(request.json.get('old_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) new_password = sha512_crypt.encrypt(request.json.get('new_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) token = request.json.get('token') # Not everything filled in if username == None or old_password == None or new_password == None or token == None: abort(400) # Verifiy token token_credentials = db_manager.verify_auth_token(token=token) if token_credentials is None: return json.dumps({ 'username':'******' }) elif not db_manager.check_password(token_credentials[0], token_credentials[1]): return json.dumps({ 'username':'******'}) elif token_credentials[0] != username: abort(401) if db_manager.check_password(username, old_password): db_manager.change_password(username, old_password, new_password) return "Changed password" else: return "ERROR, Wrong password"
def change_password(): db_manager = DatabaseManager() username = request.json.get("username") old_password = sha512_crypt.encrypt( request.json.get("old_password"), salt=app.config["SECURITY_PASSWORD_SALT"], rounds=5000 ) new_password = sha512_crypt.encrypt( request.json.get("new_password"), salt=app.config["SECURITY_PASSWORD_SALT"], rounds=5000 ) token = request.json.get("token") # Not everything filled in if username == None or old_password == None or new_password == None or token == None: abort(400) # Verifiy token token_credentials = db_manager.verify_auth_token(token=token) if token_credentials is None: abort(401) elif not db_manager.check_password(token_credentials[0], token_credentials[1]): abort(401) elif token_credentials[0] != username: abort(401) if db_manager.check_password(username, old_password): db_manager.change_password(username, old_password, new_password) return response_cache_header("Changed password", cache_control="no-cache") else: return response_cache_header("ERROR, Wrong password", cache_control="no-cache")
def save(self, *args, **kwargs): """ hash password on change or create """ try: e = EmailUser.objects.get(pk=self.pk) if not e.password == self.password: self.password = sha512_crypt.encrypt(self.password) except EmailUser.DoesNotExist: self.password = sha512_crypt.encrypt(self.password) super(EmailUser, self).save(*args, **kwargs)
def hashpw(passw, scheme = 'sha512_crypt'): """ Returns a hashed form of given password. Default scheme is sha512_crypt. """ if scheme == 'sha512_crypt': return sha512_crypt.encrypt(passw) elif scheme == 'sha': return '{SHA}' + b64encode(sha1(passw).digest()) return sha512_crypt.encrypt(passw)
def hashpw(passw, scheme="sha512_crypt"): if scheme == "sha512_crypt": return sha512_crypt.encrypt(passw) elif scheme == "crypt": salt = "$1$" + "".join(random.sample(string.ascii_uppercase+string.digits, 8)) + "$" return "{CRYPT}" + crypt.crypt(passw, salt) elif scheme == "ssha": salt = os.urandom(32) return "{SSHA}" + base64.b64encode(hashlib.sha1(passw + salt).digest() + salt) return sha512_crypt.encrypt(passw)
def genrate_vote(self): a_1 = 0 a_2 = 1 share_common = -(random.randint(1, 1000)) share_0 = -(share_common) share_1 = share_0 + 1 uid = ObjectId() env1 = CryptContext.encrypt(str(enc(0)) + str(enc(share_0)) + str(uid)) env2 = CryptContext.encrypt(str(enc(1)) + str(enc(share_1)) + str(uid)) self.__add__voter((env1, 0)) self.__add__voter((env1, 1)) return env1, env2
def donewpass(): if (lenow >= 4): newpass_char_name = msg_split[1] newpass_password = msg_split[2] newpass_new_password = msg_split[3] self.db = DBPool('mrpg.db') char_exists = yield self.db.does_char_name_exist(newpass_char_name) self.db.shutdown("") if(char_exists[0][0] == 0): self.privateMessage(user, "There is not a character by that name.") else: self.db = DBPool('mrpg.db') passhash = yield self.db.get_password(newpass_char_name) passhash = passhash[0][0] self.db.shutdown("") if(sc.verify(newpass_password, passhash)): hash = sc.encrypt(newpass_new_password) hash '$6$rounds=36122$kzMjVFTjgSVuPoS.$zx2RoZ2TYRHoKn71Y60MFmyqNPxbNnTZdwYD8y2atgoRIp923WJSbcbQc6Af3osdW96MRfwb5Hk7FymOM6D7J1' self.db = DBPool('mrpg.db') self.db.executeQuery("UPDATE users SET password = ? WHERE char_name = ?",(hash, newpass_char_name)) self.db.shutdown("") self.privateMessage(user, "You have changed your password.") else: self.privateMessage(user, "Password incorrect.") else: self.privateMessage(user, "Not enough information was supplied.")
def encrypt_password(password): salt = (sha1(urandom(16)).hexdigest())[:16] protectedPassword = sha512.encrypt(password, rounds=5000, salt=salt, implicit_rounds=True) return protectedPassword
def hash_password(self, password): """ :param password: :return: """ self.password_hash = sha512_crypt.encrypt(password)
def do_login(): # This post function will create the first administrator if there is no user database. # As a safety measure check if the auth.db file exists if os.path.isfile(os.path.dirname(os.path.abspath(__file__)) + "/lib/auth.db"): # Userdatabase is found! # Kick user away from page. response.status = 303 response.set_header('Location', '/logout') else: # Get the user details from the registration form. username = request.forms.get('username') password = request.forms.get('password') # Hash the password. hash = sha512_crypt.encrypt(password) # Create the sqlite database with the right path. con = sqlite3.connect(config["paths"]["file_auth_database"]) # Save the administrator in the database. with con: cur = con.cursor() cur.execute("CREATE TABLE secure_login(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Username TEXT NOT NULL UNIQUE, Password BLOB NOT NULL, SessionID BLOB UNIQUE, SessionStartTime BLOB)") cur.execute("INSERT INTO secure_login(ID,Username,Password) VALUES (?,?,?)", (1,username,hash)) # Now redirect the user back to the correct page. response.status = 303 response.set_header('Location', '/')
def sign_up(): """ user registration route """ if not current_user.is_admin and not APP.config['REGISTRATION_FLAG']: flash('Sorry, user registration is disabled.') return redirect(url_for('index')) if current_user.is_authenticated: flash('You are already logged in!') return redirect(url_for('index')) form = SignupForm(request.form) if request.method == 'POST' and form.validate(): form_user = form.username.data.lower() form_email = form.email.data.lower() user_already_exists = User.query.filter(( User.username == form_user) | (User.email == form_email)).scalar() if user_already_exists: flash('Username or email is already taken.') return render_template('signup.html', form=form) user = User(form.username.data.lower(), form.email.data.lower(), sha.encrypt(form.password.data)) DB.session.add(user) DB.session.commit() flash('Thanks for registering, {}!'.format(user.username)) return redirect(url_for('login')) return render_template('signup.html', form=form)
def register(): db_manager = DatabaseManager() username = request.json.get('username') password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) email = request.json.get('email') # Check if everything filled in if username is None or password is None or email is None: return abort(400) # missing arguments # Check if already exists elif db_manager.username_exists(username) or db_manager.email_exists(email): # username and/or email do already exist return response_cache_header("ERROR, username and/or email do already exist", cache_control="no-cache") else: db_manager.create_user(username=username, password_hash=password, email=email, email_verified=False) # Email verification token = generate_confirmation_token(email) confirm_url = url_for('verify_email', token=token, _external=True) html = render_template('email.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(email, subject, html) return response_cache_header("Successfully created user, please verify email.\n", cache_control="no-cache")
def resetVerifyCheck(key): url_serial = URLSafeSerializer( "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg==" ) timed_serial = TimedSerializer( "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg==" ) status = None try: key = timed_serial.loads(key, max_age=300) key = url_serial.loads(key) username = str(sanitize(key[0])) password = sha512_crypt.encrypt(sanitize(key[1])) except: status = "Oops, The Link Has Expired..!!" return status cursor, dbconn = dbConnection() query = "UPDATE users SET password = %s WHERE username = %s" try: cursor.execute(query, (password, username)) dbconn.commit() status = "Password Updated Successfully..!!" except: dbconn.rollback() status = "Oops, Something Went Wrong Please Try Again..!!" cursor.close() dbconn.close() return status
def edit_user(id): if 'admin' in fl.session: user = ml.User.query.get(id) if fl.request.method == 'GET': if user: return fl.render_template('edit-user.html', user=user) else: return fl.abort(404) else: # get the form dets fname = fl.request.form['fname'] lname = fl.request.form['lname'] email = fl.request.form['email'] lang = fl.request.form['language'] pw_raw = fl.request.form['pw_raw'] try: admin = fl.request.form['admin'] except KeyError: admin = None # encrypt pw_hashed = sha512_crypt.encrypt(pw_raw) # convert to bool if lang == '1': lang = False elif lang == '2': lang = True # check whether they are the same as before if not fname == "": if not fname == user.fname: user.fname = fname if not lname == "": if not lname == user.lname: user.lname = lname if not email == "": if not email == user.email: user.email = email if not lang == "": if not lang == user.language: user.language == lang # only run this last part if you're an admin if 'admin' in fl.session: if not admin == user.admin: if admin == 'on': user.admin = True else: user.admin = False if not pw_raw == "": if not pw_hashed == user.pw_hashed: user.pw_hashed = pw_hashed db.db_session.commit() next = fl.request.args.get('next') fl.flash(user.fname + "'s details updated", 'success') return fl.redirect(fl.url_for('manage')) else: fl.abort(403)
def generate_yaml( usernames, password_length ): yml = "---\n{}:\n".format( YAML_PARENT_VARIABLE ) for user in usernames: username, plaintext_pw = get_username_and_password( user, password_length ) password_hash = sha512_crypt.encrypt( plaintext_pw ) yml += " {}: {} # {}\n".format( username, password_hash, plaintext_pw ) return yml
def signup(): if request.method == "POST": name = request.form['name'] username = request.form['username'] email = request.form['email'] password = request.form['password'] confirm = request.form['confirm'] secure_password = sha512_crypt.encrypt(str(password)) Session = sessionmaker(bind=engine) s = Session() query = s.query(User_reg).filter( User_reg.username.in_([session.get('username')])) result = query.first() # usernamedata = db.execute("SELECT username FROM all_users WHERE username=:username", {"username":username}).fetchone() if result is None: if password == confirm: user = User_reg(name=name, username=username, email=email, password=password, confirm=secure_password) db.add(user) db.commit() flash("You are registered and can now login", "success") return redirect(url_for('home')) else: flash("Password does not match", "danger") return render_template('signup.html') else: flash("User already exists, please login or contact admin", "danger") return render_template('login.html') return render_template('signup.html')
def create_account(): if fl.request.method == 'GET': return fl.render_template('create_account.html') else: #get form data fname = fl.request.form['fname'] lname = fl.request.form['lname'] email = fl.request.form['email'] lang = fl.request.form['language'] pw_raw = fl.request.form['pw_raw'] # hash the password pw_hashed = sha512_crypt.encrypt(pw_raw) # convert to bool if lang == '1': lang = False elif lang == '2': lang = True # create user object and then commit to db new_user = ml.User(fname=fname, lname=lname, email=email, language=lang, pw_hashed=pw_hashed, admin=False) db.db_session.add(new_user) db.db_session.commit() fl.flash('success', 'User created.') # take us back to the login page. return fl.redirect(fl.url_for('login'))
def reset_hash(): global client reset_warning() NewPasswd = "1234" NewPasswd = raw_input("\nInput new password and press <enter>: ") # Create 8 char random salt SHA512_Salt = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)) # Create SHA512crypt hash of password SHA512_Passwd = sha512.encrypt(NewPasswd, rounds=5000, salt=SHA512_Salt) # Load database 'ace' db = client.ace # Get cursor for searching collection cursor = db.admin.find() for document in cursor: print "\nAttempting to recover login...\n" print "Login: "******"name": login}, {'$set': {"x_shadow": SHA512_Passwd}}) print "Password reset to: " + NewPasswd
def authenticate(): db_manager = DatabaseManager() username = request.json.get('username') password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) if username and password: if db_manager.get_user(username): if db_manager.get_user(username).get('email_verified'): # Check password if db_manager.check_password(username, password): return json.dumps({ "token": db_manager.generate_auth_token( username, password).decode("utf-8") }) else: return "ERROR, Email not verified" else: return "ERROR, User not found" else: return Response('Login!', 401, {'WWW-Authenticate': 'Basic realm="Login!"'})
def registerUser(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username = request.json.get('username', None) password = request.json.get('password', None) secretKey = request.json.get('secretKey', None) access = request.json.get("access", None) if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 if not secretKey: return jsonify({"msg": "Missing secret key"}), 400 if secretKey != Config.UserRegisterSecret: return jsonify({"msg": "Wrong key"}), 400 pw_hash = sha512_crypt.encrypt(password) newUser = { "id": username, "UserId": username, "Password": pw_hash, "Access": access } AquaUser.create_item(newUser) return "New user, {}, created!".format(username)
def write(self,values): #raise Warning(values) if values.get('password') and not values.get('dovecot_password',False): _logger.info('creates dovecot_password from %s' % values) from passlib.hash import sha512_crypt values['dovecot_password'] = sha512_crypt.encrypt(values.get('password')) return super(res_users, self).write(values)
def authenticate(): db_manager = DatabaseManager() username = request.json.get("username") password = sha512_crypt.encrypt( request.json.get("password"), salt=app.config["SECURITY_PASSWORD_SALT"], rounds=5000 ) if username and password: if db_manager.get_user(username): if db_manager.get_user(username).get("email_verified"): # Check password if db_manager.check_password(username, password): token = db_manager.generate_auth_token(username.lower(), password).decode("utf-8") user_id = db_manager.get_user(username).get("id") return response_cache_header(json.dumps({"token": token, "success": True})) else: return response_cache_header( json.dumps({"error": "Incorrect password and/or username", "success": False}), cache_control="no-cache", ) else: return response_cache_header( json.dumps({"error": "Email not verified", "success": False}), cache_control="no-cache" ) else: return response_cache_header( json.dumps({"error": "User does not exist", "success": False}), cache_control="no-cache" ) else: return Response("Login!", 401, {"WWW-Authenticate": 'Basic realm="Login!"'})
def register(): db_manager = DatabaseManager() username = request.json.get('username') password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000) email = request.json.get('email') # Check if everything filled in if username is None or password is None or email is None: return "ERROR, not everything filled in" # missing arguments # Check if already exists elif db_manager.username_exists(username) or db_manager.email_exists( email): return "ERROR, username and/or email do already exist" # username and/or email do already exist else: db_manager.create_user(username=username, password_hash=password, email=email, email_verified=False) # Email verification token = generate_confirmation_token(email) confirm_url = url_for('verify_email', token=token, _external=True) html = render_template('email.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(email, subject, html) return "Successfully created user, please verify email.\n"
def get_password_hash(password, salt='THESALTISsaltyLi', rounds=99999): """ used to obtain a users password hash, since password should not be stored in the database explicitly this function makes use of the sha512_crypt algorithm to make hashes with the default rounds. """ return sha512_crypt.encrypt(password, salt=salt, rounds=rounds)
def processRegistration(form): username = sanitize(form.username.data) password = sha512_crypt.encrypt(sanitize(form.password.data)) email = sanitize(form.email.data) fullname = sanitize(form.fullname.data) contact = (sanitize(form.contact.data)) or None reviewer = form.reviewer.data reviewer_choice = sanitize(str(form.reviewer_choice.data)) cursor, dbconn = dbConnection() status = None query = "SELECT * FROM users WHERE username = %s" query_result = cursor.execute(query, [username]) if int(query_result) > 0: status = "Plz..Choose A Different Username..!!" else: try: query = "INSERT INTO users(username, password, fullname, email_id, contact_no) VALUES(%s, %s, %s, %s, IFNULL(%s, DEFAULT(contact_no)));" query_result = cursor.execute( query, (username, password, fullname, email, contact)) if reviewer == True: query = "INSERT INTO reviewers(user_id, subject) VALUES(LAST_INSERT_ID(), %s)" query_result = cursor.execute(query, [reviewer_choice]) dbconn.commit() status = 0 except: dbconn.rollback() status = "Oops.!! Something Went Wrong, Plz Try Again..!!" cursor.close() dbconn.close() return status
def set_password(session, username, new_password): new_hash = sha512_crypt.encrypt(new_password) u = User.get(session, username) if u is not None: u.passwd = new_hash
def resetdb(): """Destroys and creates the database + tables.""" metadata = sa.MetaData() metadata.reflect(engine) for tbl in reversed(metadata.sorted_tables): tbl.drop(engine) # if not database_exists(DB_URL): # print('Creating database.') # create_database(DB_URL) print('Creating tables.') # import the models used to describe the tables we're creating (using the # ORM). Link: http://flask-sqlalchemy.pocoo.org/2.3/models/ import models Base.metadata.create_all(bind=engine) db_session.commit() print('Integrating models.') # create user object and then commit to db from passlib.hash import sha512_crypt pw_hashed = sha512_crypt.encrypt("admin") pw_hashed_an = sha512_crypt.encrypt("test") new_admin = models.User(fname="Johnny", lname="Admin", email="*****@*****.**", language=False, pw_hashed=pw_hashed, admin=True, confirmed=True) new_analyst = models.User(fname="Johny", lname="Test", email="*****@*****.**", language=True, pw_hashed=pw_hashed_an, admin=False) db_session.add(new_admin) db_session.add(new_analyst) update = models.Admin() new_search_names = models.Search_Names(name="Factiva") update.search_names.append(new_search_names) db_session.add(update) db_session.commit() print("Creating an admin user.") print("Creating an test user.") print("Creating a new search type")
def linux_hash(secret, salt=None): '''Generate Linux password hash''' if salt is None: salt = ''.join(random.choice(ALPHABET) for i in range(8)) hashed = sha512_crypt.encrypt(secret=secret, salt=salt, rounds=5000, implicit_rounds=True) return '{0}'.format(hashed)
def add(self, uid, pwd, sp_id, extra={}): if uid not in self.users: self.users[uid] = { 'pwd': sha512_crypt.encrypt(pwd), 'sp': sp_id, 'attrs': extra } self._save()
def create(self): created = datetime.datetime.utcnow() if self.checkFields(): self.request.json['password'] = sha512_crypt.encrypt(self.request.json['password']) print self.request.json return self.mc.create(self.request, created) else: abort(500)
def hash_password(self, password): """ :type password: str :rtype: str """ if not password.startswith('sha512|'): password = '******' % sha512_crypt.encrypt(password) return password
def post(self): if request.form['password1'] != request.form['password2']: return redirect('/passwords', 501) user = User.query.filter_by(username=g.user.username).first() user.password = sha512_crypt.encrypt(request.form['password1']) db.session.commit() return redirect('/')
def make_pass(passwd=None): # generate password using crypt()'s SHA-512 method, randomized salt and # randomized number of rounds. if passwd is None: passwd = randomized_string(17) salt = randomized_string(16, ( './' + string.letters + string.digits)) iterations = random.randint(40000, 80000) return '{CRYPT}' + sha512_crypt.encrypt(passwd, salt=salt, rounds=iterations)
def post_create_user(): # This post script will create a new user in the database or modify an existing one. # Request the selections the user has made in the HTML form. submit_action = request.forms.getall('submit_btn') if 'create' in submit_action: # Get the user details from the registration form. new_username = request.forms.get('new_uname') new_password = request.forms.get('new_passwd') new_password_check = request.forms.get('new_passwd_check') # Some serverside checks on the user input for the required fields to protect the server from invalid input. if len(new_username) == 0: return template('create_user', url=url, config=config, notification='The username field is required.') if len(new_password) == 0: return template('create_user', url=url, config=config, notification='The password field is required.') if new_password != new_password_check: return template('create_user', url=url, config=config, notification='Password mismatch.') # Hash the password. hash = sha512_crypt.encrypt(new_password) # Generate unique session ID. session_start_time = str(datetime.datetime.now()) secret = sha512_crypt.encrypt(session_start_time) # Connect to the database. conn = sqlite3.connect(config["paths"]["file_auth_database"]) c = conn.cursor() # Save new user in the database. c.execute("INSERT INTO `secure_login`(`ID`,`Username`,`Password`) VALUES (?,?,?)", (None, new_username, hash)) conn.commit() c.close() # Redirect. response.status = 303 response.set_header('Location', '/users') else: # Redirect. response.status = 303 response.set_header('Location', '/users')
def hashpw(passw, scheme='sha512_crypt'): """ Returns a hashed form of given password. Default scheme is sha512_crypt. Accepted schemes: sha512_crypt, bcrypt, sha (deprecated) """ if scheme == 'sha512_crypt': return sha512_crypt.encrypt(passw) elif scheme == 'bcrypt': # TODO: rounds should be configurable return bcrypt.encrypt(passw, rounds=12) # This scheme should probably be dropped to avoid creating new # unsaltes SHA1 hashes. elif scheme == 'sha': import warnings warnings.warn( 'SHA1 as a password hash may be removed in a future release.') return '{SHA}' + b64encode(sha1(passw).digest()) return sha512_crypt.encrypt(passw)
def signup(): form = SignupForm() if form.validate_on_submit(): passhash = sha512_crypt.encrypt(sha384(request.form["password"]).hexdigest()) udata = User(request.form["username"], passhash, request.form["email"]) db.session.add(udata) db.session.commit() return redirect(url_for("index")) return render_template("signup.j2", form=form)
def generate_password_hashes(self, password): """ Generate password hashes with SHA1, SHA-256 """ self.sha512 = sha512_crypt.encrypt(password) self.pbkdf2_sha256 = make_password(password, hasher='pbkdf2_sha256') self.save()
def hashpw(passw, scheme = 'sha512_crypt'): """ Returns a hashed form of given password. Default scheme is sha512_crypt. Accepted schemes: sha512_crypt, bcrypt, sha (deprecated) """ if scheme == 'sha512_crypt': return sha512_crypt.encrypt(passw) elif scheme == 'bcrypt': # TODO: rounds should be configurable return bcrypt.encrypt(passw, rounds=12) # This scheme should probably be dropped to avoid creating new # unsaltes SHA1 hashes. elif scheme == 'sha': import warnings warnings.warn( 'SHA1 as a password hash may be removed in a future release.') return '{SHA}' + b64encode(sha1(passw).digest()) return sha512_crypt.encrypt(passw)
def create_tables(): """Works the models into the db in using the ORM""" print('Creating tables.') # import the models used to describe the tables we're creating (using the # ORM). Link: http://flask-sqlalchemy.pocoo.org/2.3/models/ import models Base.metadata.create_all(bind=engine) db_session.commit() print('Integrating models.') # create user object and then commit to db from passlib.hash import sha512_crypt pw_hashed = sha512_crypt.encrypt("admin") pw_hashed_an = sha512_crypt.encrypt("test") new_admin = models.User(fname="Johnny", lname="Admin", email="*****@*****.**", language=False, pw_hashed=pw_hashed, admin=True, confirmed=True) new_analyst = models.User(fname="Johny", lname="Test", email="*****@*****.**", language=True, pw_hashed=pw_hashed_an, admin=False) db_session.add(new_admin) db_session.add(new_analyst) update = models.Admin() new_search_names = models.Search_Names(name="Factiva") update.search_names.append(new_search_names) db_session.add(update) print("Creating an admin user.") print("Creating an test user.") print("Creating a new search type") week = models.Frequencies() week.name = "Weekly" week.days_in_freq = 7 db_session.add(week) print("Adding weekly frequency") db_session.commit()
def update_user(self, username, password=None, status_name=None, roles_list=None, email=None): """ update_user :: Self -> String -- ^ users's pseudo -> Maybe String -- ^ new password -> Maybe String -- ^ account status name -> Maybe [String] -- ^ list of roles names -> Maybe String -- ^ new email -> IO Map String String -- ^ request info ================================================ This function updates an user object in database """ ret = {} ret_code = HTTP_OK usr = self.ormdb.query(User).filter_by(pseudo=username).first() if usr is not None: try: if password is not None: usr.passwhash = sha512_crypt.encrypt(password) if status_name is not None: c_stat = self.ormdb.query(Status)\ .filter_by(name=status_name).first() if c_stat is not None: usr.status = c_stat t_roles = [] if roles_list is not None: for role_name in roles_list: c_role = self.ormdb.query(Role) \ .filter_by(name=role_name).first() if c_role is not None: t_roles.append(c_role) usr.roles = t_roles if email is not None: usr.email = email ret = usr.to_dict() self.ormdb.commit() except Exception as e: logger.exception('user could not be updated') ret_code = HTTP_BAD_REQUEST ret = {ERROR_KEY: 'user could not be updated'} else: ret_code = HTTP_NOT_FOUND ret = {ERROR_KEY: 'user does not exist'} return (ret, ret_code)
def _generate_hashed_password(password): salt = "".join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(64)) return { 'hash': sha512_crypt.encrypt((password + salt).encode("utf-8"), rounds=40000), 'salt': salt }
def login(): login_form = LoginForm.LoginForm(request.form) if request.method == 'POST' and login_form.validate(): username = login_form.username.data password = sha512_crypt.encrypt(str(login_form.password.data), salt='f4773nb01m30w', rounds=20180123) return render_template('pages/success.html') return render_template('pages/login.html', form=login_form)
def _password_crypt_sha512(secret_id=None, site=None): if DUMMY_MODE: return "TEAMVAULT_DUMMY_CONTENT" else: secret = _fetch_secret(site, secret_id) return sha512_crypt.encrypt( secret['data']['password'], salt=sha512(secret_id.encode('utf-8')).hexdigest()[:16], rounds=5000, )
def saltAndHash(self, data): ''' Salt and hash a plaintext password using SHA512 algorithm Args: data (string): a plaintext password Returns: A string containing the salted hash of the password ''' return sha512_crypt.encrypt(data)
def pwdset(_n, name, passw): pwhash = sha512_crypt.encrypt(passw) shadow_entry = shadow % (name, pwhash) dbsh = bsddb3.btopen("shadow.db") dbsh[".%s" % name] = shadow_entry dbsh["0%d" % _n] = shadow_entry; dbsh.sync()
def hash_password(string): """Returns hash of string per passlib SHA512 encryption :param string: password to hash :type string: str | None """ new_hash = sha512_crypt.encrypt(string) byte_str = new_hash.encode('ascii') sys.stdout.buffer.write(byte_str+b'\n') return new_hash
def hash_password(string): """Returns hash of string per passlib SHA512 encryption :param string: password to hash :type string: str | None """ new_hash = sha512_crypt.encrypt(string) byte_str = new_hash.encode('ascii') sys.stdout.buffer.write(byte_str + b'\n') return new_hash
def testPass(cryptPass): salt = cryptPass[3:11] dictFile = open('dictionary.txt','r') for word in dictFile.readlines(): cryptWord = word.strip('\n') cryptWord = sha512_crypt.encrypt(cryptWord, salt=salt, rounds=5000) if (cryptWord == cryptPass): print "[+] Found Password: "******"\n" return print "[-] Password Not Found.\n" return
def test_hash(self): salt = 'qwerty' password = "******" value_sha256 = sha256_crypt.encrypt(password, salt=salt, rounds=5000) value_sha512 = sha512_crypt.encrypt(password, salt=salt, rounds=5000) self.assertEqual(value_sha256, '$5$qwerty$LsogXlvrRvdIKby1vMIPLn3PxErB6CooS9lzWeiFfD4') self.assertEqual(value_sha512, '$6$qwerty$yKc2cc4EDSNgZNqg.gSoVLcCI5QWuf4xCW8V0VdOVzFHHtSw.fsytKQl2g.WUIjDwJVdGD1Tw8g0Y6WAfnR1O1')
def create_user(**kwargs): username = kwargs.get('username') password = kwargs.get('password') email = kwargs.get('email') hash = sha512_crypt.encrypt(password) user = database.User(username=username, hash=hash, email=email) if database.User.objects().count() == 0: user.admin = True user.save() login_user(user)
def write(self,values): #raise Warning(values) if values.get('password') and not values.get('dovecot_password',False): _logger.info('creates dovecot_password from %s' % values) from passlib.hash import sha512_crypt values['dovecot_password'] = sha512_crypt.encrypt(values.get('password')) return super(res_users, self).write(values) #~ @api.one #~ def unlink(self): user_id = self.env['res.users'].search([('login','=',self.login)]).id postfix_alias_id = self.env['postfix.alias'].search([('user_id', '=', self.id)]).unlink()
def register(fname, lname, email, password): enc_password = sha512_crypt.encrypt(password) command = "INSERT INTO Users(FirstName, LastName, Email, Password, DateJoined) VALUES(%s, %s, %s, %s, NOW())" try: cur = con.cursor() cur.execute(command, (fname, lname, email, enc_password)) con.commit() except mdb.Error, e: if con: con.rollback()
def generate(self, cli_object): if cli_object.salt is not False: if cli_object.rounds is not False: try: generatedhash = sha512_crypt.encrypt(cli_object.plaintext, rounds=int(cli_object.rounds), salt=cli_object.salt) return generatedhash except ValueError: print helpers.color("sha512_crypt and sha512_crypt require at least 1000 rounds.", warning=True) print helpers.color("[*] Running with default of 60000 rounds.", warning=True) generatedhash = sha512_crypt.encrypt(cli_object.plaintext, salt=cli_object.salt) return generatedhash else: generatedhash = sha512_crypt.encrypt(cli_object.plaintext, salt=cli_object.salt) return generatedhash else: if cli_object.rounds is not False: try: generatedhash = sha512_crypt.encrypt(cli_object.plaintext, rounds=int(cli_object.rounds)) return generatedhash except ValueError: print helpers.color("[*] Warning: sha512_crypt and sha512_crypt require at least 1000 rounds.", warning=True) print helpers.color("[*] Running with default of 60000 rounds.", warning=True) generatedhash = sha512_crypt.encrypt(cli_object.plaintext) return generatedhash else: generatedhash = sha512_crypt.encrypt(cli_object.plaintext) return generatedhash return