def registration(): def regsend(emailrecip, link, firstname): sender_email = "*****@*****.**" receiver_email = str(session['username']) password = "******" message = MIMEMultipart("alternative") message["Subject"] = "Welcome! Please complete registration" message["From"] = sender_email message["To"] = receiver_email # Create the plain-text and HTML version of your message text = """\ """ changetemplate = open("templates/emailreg.html", "rt") ### read template and replace name html = changetemplate.read() html = html.replace('username', firstname) html = html.replace('replacelink', link) changetemplate.close() # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(part2) # Create secure connection with server and send email context = ssl._create_unverified_context() with smtplib.SMTP_SSL( "webmail.nullphish.com", 465, context=ssl._create_unverified_context()) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) try: if request.method == "POST": firstname = request.form.to_dict()['firstname'] lastname = request.form.to_dict()['lastname'] username = request.form.to_dict()['email'] business = request.form.to_dict()['business'] session['username'] = username password = request.form.get('password') if len(password) < 10: flash('Please use a password with at least 10 characters') return render_template("register.html") password = str(request.form.get('password')) repeat = str(request.form.get('password')) code = request.form.to_dict()['code'] if repeat != password: flash('Your passwords do not match. Please try again.') return render_template("register.html") con = sqlite.connect('db/db1.db') if code != 'goat': if code != 'kdb': flash('Incorrect registration code') return render_template("register.html") else: pass with con: cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute("SELECT * FROM users WHERE username LIKE (?);", (session['username'], )) result = cur.fetchone() con.close if result == None: del repeat password = argon2.using(rounds=4).hash( request.form.get('password')) cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute( "INSERT INTO users (username, password, firstname, lastname, business, role, validated, notify) VALUES (?, ?, ?, ?, ?, 'admin', 0, 1);", ( username, password, firstname, lastname, business, )) cur.execute( "INSERT INTO userperm (username, role, enroll, view, remove, email) VALUES (?, 'admin', 1, 1, 1, 1);", (username, )) con.commit() con.close() gc.collect() del password session['role'] = 'admin' session['logged_in'] = True session['username'] = username emailrecip = username email = username newtoken = generate_confirmation_token(email) link = 'https://app.nullphish.com/register?token=' + newtoken regsend(emailrecip, link, firstname) flash( 'Success! Please check your email for a confirmation link.' ) return render_template('register.html') if request.method == 'GET': if request.args.get('token'[:]) != None: try: newtoken = request.args.get('token'[:]) email = str(confirm_token(newtoken)) if '@' in email: con = sqlite.connect('db/db1.db') with con: cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute( 'update users set validated = 1 where username = (?);', (email, )) con.close() return redirect('/login') else: flash( 'The confirmation link is invalid or has expired (60 minutes)' ) return render_template("register.html") except: flash( 'The confirmation link is invalid or has expired (60 minutes)' ) return render_template("register.html") return render_template("register.html") except Exception as e: return (str(e)) return render_template("register.html")
def __init__(self, name, username, password, email): self.name = name self.username = username self.email = email self.password = argon2.using(time_cost=160, memory_cost=10240, parallelism=8).hash(password)
def set_password(self, password: str): self.password_hash = argon2.using(salt_len=40, rounds=4).hash(password)
def set_password(self, password): """ Set password. """ self.password = argon2.using(rounds=4).hash(password + self.salt)
def encrypt_function(unencrypted_value, salt_string): encrypted_value = argon2.using(rounds=5, salt=salt_string).hash(unencrypted_value) return encrypted_value
def t_argon2(plain_password): return argon2.using(rounds=256, memory_cost=1024).hash(plain_password)
def set_password(self, password): self.password_hash = argon2.using(rounds=10, digest_size=32, salt_size=32, memory_cost=128000).hash(password)
def _hash_password(password): return argon2.using(rounds=ROUNDS).hash(password)
def hash_password(password): sha_hash = sha512(password.encode("utf-8")) argon2_hash = argon2.using(rounds=3).hash(sha_hash.digest()) argon2_hash = argon2_hash.encode() # turns string to 'bytes like object' return b64encode(argon2_hash)
def argonHash(pre_hash): return argon2.using(rounds=4).hash(pre_hash)
def loadadminprofile(): def placeholder(): print(';') def loadmessages(): con = sqlite.connect('db/db1.db') with con: con.row_factory = sqlite.Row cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute( "select id, sender, message, datesent from messages where username = (?) and business = (?);", ( session['username'], session['business'], )) currentmessages = cur.fetchall() return currentmessages try: currentmessages = loadmessages() except: print('no messages-syslog') pass if request.method == "POST": if 'password' in request.form: if len(str(request.form['password'])) > 8: if request.form['password'] != request.form['repeat']: flash('Your passwords do not match. Please try again.', 'category2') return render_template("adminprofile.html") else: password = argon2.using(rounds=4).hash( request.form.get('password')) con = sqlite.connect('db/db1.db') with con: cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute( "UPDATE users set password = (?) WHERE username = (?);", ( password, session['username'], )) con.commit() gc.collect() flash('Password Changed!', 'category2') return render_template( "adminprofile.html", username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname']) else: flash('Password must be 8 characters or more.', 'category2') return render_template("adminprofile.html", username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname']) return render_template("adminprofile.html", currentmessages=currentmessages, username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname'])
def hash_func(pwd_string): return argon2.using(rounds=4).hash(pwd_string)
def argon2_find_cost_calculator(self, max_time=None): """ Finds a good cost factor for the current system. It tests various factors and finds the most expensive one for this system that is still around 300 milliseconds, or whatever max_time is set to or MAX_DURATION. :param force_update: If true, will force a new search. :return: """ if max_time is None: max_time = MAX_DURATION else: try: max_time = int(max_time) except Exception as e: max_time = MAX_DURATION max_time = max_time * .95 memory_base = 1 memory_min = 11 memory_max = 17 rounds_min = 0 rounds_max = 16 duration = -1 skip = 0 rounds_best = 8 memory_best = 10 duration_best = 300 for memory_step in range(memory_min, memory_max): for rounds in range(rounds_min + round(memory_step * 0.4), rounds_max): # We implement a skipper if we blast through some of the early checks. if skip > 0: skip -= 1 duration = 0 continue max_time_skip = duration / 4 if duration > 0 and duration < max_time * 0.1: skip = 5 if (rounds + skip) > rounds_max: skip = rounds_max - rounds duration = 0 continue if duration > 0 and duration < max_time * 0.125: skip = 4 if (rounds + skip) > rounds_max: skip = rounds_max - rounds duration = 0 continue if duration > 0 and duration < max_time * 0.25: skip = 3 if (rounds + skip) > rounds_max: skip = rounds_max - rounds duration = 0 continue if duration > 0 and duration < max_time * 0.375: skip = 2 if (rounds + skip) > rounds_max: skip = rounds_max - rounds duration = 0 continue if duration > 0 and duration < max_time * 0.5: skip = 1 duration = 0 continue start = time() memory_cost = memory_base << memory_step argon2.using(rounds=rounds, memory_cost=memory_cost).hash("testingpassword!") end = time() duration = (end - start) * 1000 # print("rounds=%s, memory=%s (%s), time=%.3f" % (rounds, memory_cost, memory_step, duration)) if duration > max_time: break rounds_best = rounds memory_best = memory_step duration_best = duration # if rounds == rounds_min + round(memory_step * 0.4): # break return([rounds_best, memory_best, duration_best])
def hash_password(pwd, pep): h = argon2.using(rounds=10).hash(pwd) ph = pep.encrypt(h.encode('utf-8')) b64ph = base64.b64encode(ph) return b64ph
from passlib.hash import argon2 password = input("Ingrese la contraseña: ") # Generacion de hash h = argon2.hash(password) print("Hash: ", h) # Generacion de hash pero con un numero definido de rondas roundH = argon2.using(rounds=4).hash(password) print("Hash with 4 rounds: ", roundH) ver = argon2.verify(password, h) print("Verificacion con '{}': ".format(password), ver) bad = argon2.verify("otrapalabra", h) print("Vericicación con otra palabra que no es la contraseña ingresada: ", bad)
salt = uuid.uuid4().hex.encode('utf-8') hashed_password = hashlib.sha512(password.encode('utf-8') + salt).hexdigest() return salt.decode('utf-8'), hashed_password def sha512_salted_hash_verify(user: models.User, password: str) -> bool: hashed_password = hashlib.sha512( password.encode('utf-8') + user.salt.encode('utf-8')).hexdigest() return user.password == hashed_password hash_fns = { 1: lambda password: sha512_salted_hash(password), 2: lambda password: argon2.using(rounds=ARGON2_ROUNDS).hash(password) } hash_verify_fns = { 1: lambda user, password: sha512_salted_hash_verify(user, password), 2: lambda user, password: argon2.verify(password, user.password) } @utils.rollback_on_error def update_user_password(userid, password): user = User.query.get(userid) hash_fn = hash_fns[CURRENT_HASH_VERSION] user.hash_version = CURRENT_HASH_VERSION user.password = hash_fn(password)
def hash_password(value): return argon2.using(rounds=app.config['ARGON2_ROUNDS']).hash(value)
def encrypt(cls, value: str) -> str: if isinstance(value, str): salt = str.encode(cls.__salt) return argon2.using(rounds=4, salt=salt).hash(value) raise ValueError('The value to encrypt must to be a string.')
def __init__(self, username, password, email): self.username = username self.password = argon2.using(rounds=5).hash(password) self.email = email self.registered_on = datetime.utcnow()
def EncryptPassword(self): self.Password = argon2.using(rounds=4).hash(self.Password)
def argonHash(pre_hash): """ : Uses argon algorithm to hash a string """ return argon2.using(rounds=4).hash(pre_hash)
ident = u('pbkdf2_sha1$') checksum_size = 28 # 20 bytes -> base64 default_rounds = pbkdf2_sha1.default_rounds # NOTE: django 1.6 uses 12000 _digest = "sha1" #============================================================================= # Argon2 #============================================================================= # NOTE: as of 2019-11-11, Django's Argon2PasswordHasher only supports Type I; # so limiting this to ensure that as well. django_argon2 = uh.PrefixWrapper( name="django_argon2", wrapped=argon2.using(type="I"), prefix=u('argon2'), ident=u('argon2$argon2i$'), # NOTE: this docstring is duplicated in the docs, since sphinx # seems to be having trouble reading it via autodata:: doc= """This class implements Django 1.10's Argon2 wrapper, and follows the :ref:`password-hash-api`. This is identical to :class:`!argon2` itself, but with the Django-specific prefix ``"argon2$"`` prepended. See :doc:`argon2 </lib/passlib.hash.argon2>` for more details, the usage and behavior is identical. This should be compatible with the hashes generated by Django 1.10's :class:`!Argon2PasswordHasher` class.
if not path.exists(SALT_FILE): with open(SALT_FILE, "w") as f: f.write(secrets.token_hex(SALT_LENGTH)) if not path.exists(PARAMS_FILE): output = "" output += (input("digest_size (bytes)") or "32") + "\n" output += (input("memory_cost (kibibytes) [press enter for default]") or "512") + "\n" output += (input("rounds [default value: 2]") or "2") + "\n" output += (input("parallelism [default value: 2]") or "2") + "\n" with open(PARAMS_FILE, "w") as f: f.write(output) with open(SALT_FILE, 'rb') as tmp: salt = tmp.read() with open(PARAMS_FILE, 'r') as tmp: params = tmp.readlines() h = argon2.using( salt=salt, digest_size=int(params[0].replace('\n', '')), memory_cost=int(params[1].replace('\n', '')), rounds=int(params[2].replace('\n', '')), parallelism=int(params[3].replace('\n', ''))).hash(( getpass("Enter your password: "******"mickens") + domain) print(h.split(',p=')[1].split('$')[2])
def myprofile(): def checkpassword(): con = sqlite.connect('db/db1.db') with con: cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') try: cur.execute('select password from users where username = (?);', (session['username'], )) passwordstatus = cur.fetchone() passwordstatus = 1 return passwordstatus except: passwordstatus = None return passwordstatus passwordstatus = checkpassword() if request.method == "POST": if 'password' in request.form: if len(str(request.form['password'])) > 8: if repeat != password: flash('Your passwords do not match. Please try again.', 'category2') return render_template("userprofile.html") else: password = argon2.using(rounds=4).hash( request.form.get('password')) repeat = password = argon2.using(rounds=4).hash( request.form.get('repeat')) con = sqlite.connect('db/db1.db') with con: cur = con.cursor() cur.execute('PRAGMA key = ' + dbkey + ';') cur.execute( "UPDATE users set password = (?) WHERE username = (?);", ( password, session['username'], )) con.commit() gc.collect() flash('Password Changed!', 'category2') return render_template( "userprofile.html", username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname']) else: flash('Password must be 8 characters or more.', 'category2') return render_template("userprofile.html", username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname']) if passwordstatus == None: flash('Please create a password for this account', 'category2') flash('(password requirements: more than 10 characters)', 'category1') return render_template('userprofile.html', username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname']) return render_template("userprofile.html", username=session['username'], business=session['business'], department=session['department'], role=session['role'], firstname=session['fname'], lastname=session['lname'])
def set_password(self, plaintext): self.password = argon2.using(rounds=4).hash(plaintext)
def get_password_hash(self): from passlib.hash import argon2 hashword = argon2.using(rounds = 256, memory_cost = 1024).hash(self.password.data) app.logger.debug("hashword = %s",hashword) return hashword
def encrypt_password(password_unencrypted, salt_string): encrypted_password = argon2.using( rounds=5, salt=salt_string).hash(password_unencrypted) return encrypted_password
def get_password_hash(self, password): return argon2.using(rounds=4).hash(password)
def hashed_password(password: str) -> bytes: return argon2.using(rounds=4, salt_size=128).hash(password)
def register_user(): db = get_db() post_data = request.json try: username = post_data["Username"] password = post_data["Password"] email_address = post_data["Email"] except BadRequestKeyError: abort(400, "ERROR: malformed post request") try: token = post_data["Token"] except: return jsonify({ "success": False, "message": "Failed to retrieve reCAPTCHA token, please refresh and try again. If this issue persists, please email [email protected]" }) try: refer = post_data["Refer"] except: refer = '' captcha_model = { "secret": "6Ldx55wUAAAAAMQyfKUezVAoZM7MpPq3UReBo4qp", "response": str(token) } r = requests.post('https://www.google.com/recaptcha/api/siteverify', captcha_model) json_response = r.json() if not json_response["success"]: return jsonify({ "success": False, "message": "reCAPTCHA verification failed. Please refresh and try again. If this issue persists, please email [email protected]" }) # check that the username meets our guidelines if len(username) > 12: return jsonify({ "success": False, "message": "Username length must be no more than 12 characters." }) if not username.isalnum(): return jsonify({ "success": False, "message": "Username must be alpha numeric." }) repeat_char = re.compile(r'(.)\1\1\1\1\1') # test that the password meets our guidelines if len(password) < 8: return jsonify({ "success": False, "message": "Password length too short" }) if len(password) > 64: return jsonify({ "success": False, "message": "Password length too long" }) if repeat_char.match(password) is not None: return jsonify({ "success": False, "message": "Password has repeating characters" }) if check_digits(password): return jsonify({ "success": False, "message": "Password has incrementing numbers" }) # Uncomment this if we're gonna store sensitive data # if is_pwned_password(password): # return jsonify({"success":False,"message":"This password has been leaked in a known data breach. Please use a different password. For more info see https://haveibeenpwned.com/Passwords"}) # test that the email is valid if check_valid_email(email_address) is False: return jsonify({"success": False, "message": "Email is invalid."}) # hash the password password_hash = argon2.using(time_cost=160, memory_cost=10240, parallelism=8).hash(password) cursor = db.cursor() # --------------------------------------------------------------- # check if an account already exists with the given username sql_query = ''' SELECT * FROM users WHERE Username = %(Username)s ''' cursor.execute(sql_query, post_data) data = cursor.fetchall() if len(data) > 0: return jsonify({ "success": False, "message": "This username is already taken!" }) # check if an account already exists with the given email sql_query = ''' SELECT * FROM users WHERE Email = %(Email)s ''' cursor.execute(sql_query, post_data) data = cursor.fetchall() if len(data) > 0: return jsonify({ "success": False, "message": "This email is already taken!" }) # --------------------------------------------------------------- #add to table sql_query = ''' INSERT INTO users (Username, Email, Password, Refer) VALUES (%(username)s, %(email)s, %(password)s, %(refer)s) ''' user_entry = { "username": str(username), "email": str(email_address), "password": str(password_hash), "refer": str(refer) } cursor.execute(sql_query, user_entry) db.commit() user_id = cursor.lastrowid #generate validation id validation_id = uuid.uuid4() sql_query = ''' INSERT INTO validations(UserID, ValidationID) VALUES (%(user_id)s, %(validation_id)s) ''' validation_entry = { "user_id": str(user_id), "validation_id": str(validation_id) } cursor.execute(sql_query, validation_entry) db.commit() sql_query = ''' INSERT INTO userMedals(UserID, Type, BronzeMedals, SilverMedals, GoldMedals) VALUES (%(user_id)s, 0, 0, 0, 0), (%(user_id)s, 1, 0, 0, 0), (%(user_id)s, 2, 0, 0, 0) ''' cursor.execute(sql_query, validation_entry) db.commit() sql_query = ''' INSERT INTO accountData(UserID, XP, PuzzlerIcon) VALUES (%(user_id)s, 0, 0) ''' cursor.execute(sql_query, validation_entry) db.commit() validation_url = "https://puzzlehub.io/EmailVerify;code=" + str( validation_id) # Send validation url SENDER = "*****@*****.**" SENDERNAME = "No Reply" RECIPIENT = str(email_address) USERNAME_SMTP = json_data['email_username'] PASSWORD_SMTP = json_data['email_password'] HOST = "email-smtp.us-east-1.amazonaws.com" PORT = 587 SUBJECT = "Puzzle Hub Email Verification" BODY_TEXT = ''' Thank you for registering for an account on puzzlehub.io! Please click the following link to verify your account \n\n ''' + validation_url msg = MIMEMultipart('alternative') msg['Subject'] = SUBJECT msg['From'] = email.utils.formataddr((SENDERNAME, SENDER)) msg['To'] = RECIPIENT # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(BODY_TEXT, 'plain') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) # Try to send the message. try: server = smtplib.SMTP(HOST, PORT) server.ehlo() server.starttls() server.ehlo() server.login(USERNAME_SMTP, PASSWORD_SMTP) server.sendmail(SENDER, RECIPIENT, msg.as_string()) server.close() except Exception as e: print("Error: ", e) return jsonify({"success": True})