def register(): if 'user' in session: return redirect(url_for('home')) '''Adding users to the database''' if request.form.get("reg_username") != None: r_username = request.form.get("reg_username") r_password = request.form.get("reg_password") check_pass = request.form.get("check_password") r_question = request.form.get("reg_question") r_answer = request.form.get("reg_answer") if r_username in db.get_all_users(): flash("Username taken") elif r_password != check_pass: flash("Passwords do not match!") elif r_password.count(' ') != 0: flash("Password can not contain spaces") elif not r_username.isalnum(): flash("Username should be alphanumeric") else: if request.form.get("reg_question") != None: session['user'] = r_username db.add_userFull(r_username, md5_crypt.encrypt(r_password), r_question, md5_crypt.encrypt(r_answer)) return redirect(url_for("how")) else: session['user'] = r_username db.add_user(r_username, md5_crypt.encrypt(r_password)) return redirect(url_for("home")) return render_template('register.html')
def test_compare(self): from passlib.hash import md5_crypt obj = self.User() obj.password = Password(md5_crypt.encrypt('b')) other = self.User() other.password = Password(md5_crypt.encrypt('b')) # Not sure what to assert here; the test raised an error before. assert obj.password != other.password
def bsdnthash(): s() m = raw_input(q) from passlib.hash import bsd_nthash as mc bsd_nthash = mc.encrypt(m) print(e + bsd_nthash) s()
def scram(): s() m = raw_input(q) from passlib.hash import scram as mc scram = mc.encrypt(m) print(e + scram) s()
def atlassianspbkdf2(): s() m = raw_inpur(q) from passlib.hash import cta_pbkdf2_sha1 as mc atl_pbkdf2_sha1 = mc.encrypt(m) print(e + atl_pbkdf2_sha1) s()
def dwinepbdf2(): s() m = raw_input(q) from passlib.hash import dlitz_pbkdf2_sha1 as mc dlitz_pbkdf2_sha1 = mc.encrypt(m) print(e + dlitz_pbkdf2_sha1) s()
def cryptacularspbdf2(): s() m = raw_input(q) from passlib.hash import cta_pbkdf2_sha1 as mc cta_pbkdf2_sha1 = mc.encrypt(m) print(e + cta_pbkdf2_sha1) s()
def phpass(): s() m = raw_input(q) from passlib.hash import phpass as mc phpass = mc.encrypt(m) print(e + phpass) s()
def apachemd5crypt(): s() m = raw_input(q) from passlib.hash import apr_md5_crypt as mc apr_md5_crypt = mc.encrypt(m) print(e + apr_md5_crypt) s()
def sunmd5crypt(): s() m = raw_input(q) from passlib.hash import sun_md5_crypt as mc sun_md5_crypt = mc.encrypt(m) print(e + sun_md5_crypt) s()
def sha512crypt(): s() m = raw_input(q) from passlib.hash import sha512_crypt as mc sha512_crypt = mc.encrypt(m) print(e + sha512_crypt) s()
def md5crypt(): s() m = raw_input(q) from passlib.hash import md5_crypt as mc md5_crypt = mc.encrypt(m) print(e + md5_crypt) s()
def save(self, commit=True): mem = super(MailboxForm, self).save(commit=False) password = self.cleaned_data.get('password1') if password: mem.password = md5_crypt.encrypt(password) mem.pwd_days_time = int(time.time()) else: mem.password = self.raw_password if commit: mem.save() if password: objAttr, created = MailboxUserAttr.objects.get_or_create( mailbox_id=mem.id, domain_id=mem.domain_id, type=u"system", item=u"password") raw_password = u"hHFdxF43et:::" + password + u":::hHFdxF43et" raw_password = base64.encodestring(raw_password) objAttr.value = raw_password objAttr.save() if is_distribute_open(): task_queue = TaskQueue() proxy_data = { 'protocol': 'core_mailbox', 'data': { 'update': mem.id } } task_queue.add_task_to_queue('proxy_web_command', proxy_data) task_queue.create_trigger('proxy') clear_redis_cache() return mem
def signup(self): print(request.form) # Create the user object user = { "_id": uuid.uuid4().hex, "name": request.form.get('name'), "email": request.form.get('email'), "password": request.form.get('password') } # Encrypt the password user['password'] = md5_crypt.encrypt(user['password']) # Check for existing email address if db.Users.find_one({"email": user['email']}): return jsonify({"error": "Email address already in use"}), 400 if db.Users.insert_one(user): self.start_session(user) user_id = {"user_id": user['_id']} response = requests.post(self.base + "user/", data=user_id, headers=self.jwt_encode()) return response.json() return jsonify({"error": "Signup failed"}), 400
def type5_pw(password, salt=None): if not HAS_PASSLIB: raise AnsibleFilterError( 'type5_pw filter requires PassLib library to be installed') if not isinstance(password, string_types): raise AnsibleFilterError( "type5_pw password input should be a string, but was given a input of %s" % (type(password).__name__)) salt_chars = ansible_password._gen_candidate_chars( ['ascii_letters', 'digits', './']) if salt is not None and not isinstance(salt, string_types): raise AnsibleFilterError( "type5_pw salt input should be a string, but was given a input of %s" % (type(salt).__name__)) elif not salt: salt = random_password(length=4, chars=salt_chars) elif not set(salt) <= set(salt_chars): raise AnsibleFilterError( "type5_pw salt used inproper characters, must be one of %s" % (salt_chars)) encrypted_password = md5_crypt.encrypt(password, salt=salt) return encrypted_password
def login(self, user, data, req): salt = req.load("https://webshare.cz/api/salt/", post={'username_or_email': user, 'wst' : ""}, decode=True) if "<status>OK</status>" not in salt: self.wrongPassword() salt = re.search('<salt>(.+)</salt>', salt).group(1) password = sha1(md5_crypt.encrypt(data['password'], salt=salt)).hexdigest() digest = md5(user + ":Webshare:" + password).hexdigest() login = req.load("https://webshare.cz/api/login/", post={'digest' : digest, 'keep_logged_in' : 1, 'password' : password, 'username_or_email': user, 'wst' : ""}, decode=True) if "<status>OK</status>" not in login: self.wrongPassword() self.infos['wst'] = re.search('<token>(.+)</token>', login).group(1)
def crypt_md5(passwd): """ Returns an md5-crypt hash of a clear-text password. To get md5-crypt from ``crypt(3)`` you must pass an 8-char string starting with '$1$' and ending with '$', resulting in a 12-char salt. This only works on systems where md5-crypt is default and is currently assumed to be Linux. :param passwd: Password string to be encrypted """ import platform if platform.system() == 'Linux': import crypt import hashlib import time salt = '$1$' + hashlib.md5(str(time.time())).hexdigest()[0:8] + '$' crypted = crypt.crypt(passwd, salt) else: try: from passlib.hash import md5_crypt except ImportError: raise RuntimeError("""When not using Linux, generating md5-crypt password hashes requires the `passlib` module.""") else: crypted = md5_crypt.encrypt(passwd) return crypted
def signupAuthentication(): '''Checks if the username that the user registers with is at least four characters long and that the passwords that they entered twice are the same. If they aren't correct, then tell them to try again. If they are correct, create the account and redirect to the login.''' user_data = db.get_all_user_data() username_input = request.form.get("username") password_input = request.form.get("password") password_input2 = request.form.get("password2") #checks if there is an user with the same username if username_input in user_data: flash("Username already exists! Please pick another one!") return redirect(url_for("signup")) #checks if the user typed the same passward twice elif len(username_input) < 4: flash("Username has to be at least 4 characters!") return redirect(url_for("signup")) elif password_input != password_input2: flash("Input Same Password in Both Fields!") return redirect(url_for("signup")) elif len(password_input) < 4: flash("Password has to be at least 4!") return redirect(url_for("signup")) else: #adds the user's username and a hashed + salted #version of his password to database db.add_user(username_input, md5_crypt.encrypt(password_input)) flash("Successfully Registered, Now Sign In!") return render_template('login.html', success=True)
def reset(): if 'user' in session: return redirect(url_for('home')) '''To reset user password''' if request.form.get("reg_username") != None: r_username = request.form.get("reg_username") r_answer = request.form.get("reg_answer") r_password = request.form.get("reg_password") check_pass = request.form.get("check_password") all_usernames = db.qaDict() #Returns dict {user:answer_to_question} if r_username not in db.get_all_users(): flash("Username not found") elif r_password != check_pass: flash("Passwords do not match!") elif r_password.count(' ') != 0: flash("Password can not contain spaces") elif not r_username.isalnum(): flash("Username should be alphanumeric") else: session['user'] = r_username # checks the question and answer in the db if r_username in all_usernames: # if the hashes match if md5_crypt.verify(r_answer, all_usernames[r_username]): # changes the user password db.update_pass(r_username, md5_crypt.encrypt(r_password)) return redirect(url_for('home')) else: flash("Error occurred") return render_template('reset.html')
def save(self, *args, **kwargs): self.recipient_key = sanitize_key(self.recipient_key) if not self.recipient_key_hash: self.recipient_key_hash = md5_crypt.encrypt(self.recipient_key, salt='').encode('base64') if not self.recipient_challenge: self.recipient_challenge = os.urandom(1024).encode('base64') models.Model.save(self, *args, **kwargs)
def login(self, user, data, req): salt = req.load("https://webshare.cz/api/salt/", post={'username_or_email': user, 'wst' : ""}, decode=True) if "<status>OK</status>" not in salt: self.wrongPassword() salt = re.search('<salt>(.+)</salt>', salt).group(1) password = sha1(md5_crypt.encrypt(data["password"], salt=salt)).hexdigest() digest = md5(user + ":Webshare:" + password).hexdigest() login = req.load("https://webshare.cz/api/login/", post={'digest' : digest, 'keep_logged_in' : 1, 'password' : password, 'username_or_email': user, 'wst' : ""}, decode=True) if "<status>OK</status>" not in login: self.wrongPassword() self.infos['wst'] = re.search('<token>(.+)</token>', login).group(1)
def forgot_password(request): if (request.method == 'POST'): email = request.POST['email'] hash_email = md5_crypt.encrypt(email) url_email = hash_email[:0] + hash_email[3:] all_user = t_user.objects.all() m = 'null' user = None for users in all_user: if (users.email == email): m = 'not null' user = users break if (m == 'not null'): subject = '[Reset your password ]' text_content = '' html_content = '<h4>Hello ' + user.full_name + ',</h4><br>' \ '<p>Click the link below to reset your password</p><br>' \ '<a href="http://localhost:8000/forum/user/change_password/' + url_email + '" style="background-color: #F2711C; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px;" >RESET PASSWORD</a><br><br>' \ '<p><strong>Note : If it does not you who make this request, please ignore this email</strong></p>' \ '<hr>' \ '<p><strong>Thank You</strong></p>' \ '<p><strong>Forum Mahasiswa</strong></p>' msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email]) msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponse('not null') else: return HttpResponse('null') else: return render(request, '404.html')
def restorePassword(): pwd = request.form["passwd"] logged = False #pwd = md5_crypt.encrypt(dec_pwd) data = getData('easyrash/users/users.json') if (hasattr(flask_login.current_user, 'id')): mail = flask_login.current_user.id old_pwd = request.form["old_passwd"] logged = True else: mail = request.form["mail"] req_file = getData("easyrash/requestSetPwd.json") for i in range(len(req_file)): if (req_file[i]['mail'] == mail): req_file.pop(i) modifyData(req_file, 'easyrash/requestSetPwd.json') for key in data: if (data[key]["email"] == mail): if (logged and md5_crypt.verify(old_pwd, data[key]['pass']) == False): print("control password") return (403) data[key]["pass"] = md5_crypt.encrypt(pwd) modifyData(data, "easyrash/users/users.json") return render_template("login.html") print("bad") abort(400)
def authenticate(self, request=None, username=None, password=None): try: space_db = SpacewalkDB() result = space_db.execute_one("select * FROM web_contact WHERE LOGIN = '******'" % (username)) if config.CONFIG.get('spacewalk', 'db_backend') == 'postgresql': passwd_to_match = result[4] else: passwd_to_match = result[4] salt = passwd_to_match.split("$")[2] passwd_hash = md5_crypt.encrypt(password, salt=salt) if passwd_to_match == passwd_hash: try: user = User.objects.get(username=username) except Exception as e: _LOG.debug("User not found or exception: %s" % (str(e))) # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from settings.py will. user = User(username=username, password=password) user.is_active = True user.is_staff = False user.is_superuser = False user.save() return user return None except IndexError: _LOG.error('authentication failed, user does not exist in spacewalk') return None
def registerAuth(): # determine user type userType = request.form['userType'] # email/username and raw password from the form attribute, ID = ('username', request.form['username']) if userType == 'airline_staff' else ('email', request.form['email']) raw_pwd = request.form['password'] #cursor used to send queries cursor = conn.cursor() #executes query query = 'SELECT * FROM ' + userType + ' WHERE ' + attribute + ' = %s' cursor.execute(query, (ID)) #stores the results in a variable data = cursor.fetchone() #use fetchall() if you are expecting more than 1 data row error = None # return error message if user exists if(data): #If the previous query returns data, then user exists error = "This user already exists" return render_template('register.html', error = error) else: # hash password here password = md5_crypt.encrypt(raw_pwd) if userType == 'customer': email = ID name = request.form['name'] building_number = request.form['building_number'] street = request.form['street'] city = request.form['city'] state = request.form['state'] phone_number = request.form['phone_number'] passport_number = request.form['passport_number'] passport_expiration = request.form['passport_expiration'] passport_country = request.form['passport_country'] date_of_birth = request.form['date_of_birth'] insert = 'INSERT INTO customer VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' cursor.execute(insert, (email, name, password, building_number, street, city, state, phone_number, passport_number, passport_expiration, passport_country, date_of_birth)) elif userType == 'booking_agent': "what" email = ID booking_agent_id = request.form['booking_agent_id'] insert = 'INSERT INTO booking_agent VALUES(%s, %s, %s)' cursor.execute(insert, (email, password, booking_agent_id)) elif userType == 'airline_staff': username = ID first_name = request.form['first_name'] last_name = request.form['last_name'] date_of_birth = request.form['date_of_birth'] airline_name = request.form['airline_name'] insert = 'INSERT INTO airline_staff VALUES(%s, %s, %s, %s, %s, %s)' cursor.execute(insert, (username, password, first_name, last_name, date_of_birth, airline_name)) conn.commit() cursor.close() return render_template('index.html')
def hash_password(self, user_name, password, salt): """Creates password hash used by Webshare API""" password = hashlib.sha1( md5_crypt.encrypt(password, salt=salt).encode('utf-8')).hexdigest() digest = hashlib.md5( (user_name + ':Webshare:' + password).encode('utf-8')).hexdigest() return password, digest
def getAuthChallenge(self, publicKey): self.auth_public_key = sanitize_key(publicKey) self.auth_public_key_hash = md5_crypt.encrypt(self.auth_public_key, salt='').encode('base64') self.auth_complete = False return crypto.encrypt_rsa( self.auth_challenge, crypto.load_public_key(publicKey)).encode('base64')
def _set_password(self, username, password): password = password.encode("utf-8") crypted = md5_crypt.encrypt(password) result, output = self.call_popen(["usermod", "-p", crypted, username]) if result != 0: raise UserManagementError("Error setting password for user " "%s.\n%s" % (username, output)) return output
def clean(self): res = '' mailparts = self.username.split('@') self.local_part = mailparts[0] #self.domain = mailparts[1] self.maildir = self.username + '/' res = re.search(r"\$1\$", self.password) if not res: self.password = md5_crypt.encrypt(self.password)
def insert_to_db(line): infos = line.split() member = { "fullname": infos[0], "_id": infos[1], "password_hash": md5_crypt.encrypt(infos[1]), "created": datetime.now().__format__("%Y-%m-%d %H:%M:%S"), "last_updated": datetime.now().__format__("%Y-%m-%d %H:%M:%S"), "url_token": None, "avatar_path": None } members.insert(member)
def post(self): name = request.form.get('name', None) password = request.form.get('password', None) if not name or not password: return {'status': 'error', 'message': '用户名和密码不能为空'} user = User.getOne(User.name == name) if user: return {'status': 'error', 'message': '用户已经存在'} user = User.create(name=name, password=md5_crypt.encrypt(password)) user.save() session['user'] = user data = user.toJson() data.pop('password') return {'status': 'success', 'result': data}
def test_check_and_update(self): """ Should be able to compare the plaintext against a deprecated encrypted form and have it auto-update to the preferred version. """ from passlib.hash import md5_crypt obj = self.User() obj.password = Password(md5_crypt.encrypt('b')) assert obj.password.hash.decode('utf8').startswith('$1$') assert obj.password == 'b' assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')
def insertEsgfUser(self, userProfile): ''' Creates an ESGF user in the ESGF database from a CoG user in the CoG database.''' openid = userProfile.openid() # do NOT override ESGF database esgfUser = self.getUserByOpenid(openid) if esgfUser is None: session = self.Session() try: # encrypt password with MD5_CRYPT clearTextPwd = userProfile.clearTextPwd if clearTextPwd is not None and len(clearTextPwd)>0: encPassword = md5_crypt.encrypt(clearTextPwd) else: encPassword = None username = openid[ openid.rfind('/')+1: ] # ESGF usernames are NOT unique in the same database esgfUser = ESGFUser(firstname=userProfile.user.first_name, lastname=userProfile.user.last_name, email=userProfile.user.email, username=username, password=encPassword, dn='', openid=openid, organization=userProfile.institution, organization_type='', city=userProfile.city, state=userProfile.state, country=userProfile.country, status_code=1, verification_token=str(uuid4()), notification_code=0) session.add(esgfUser) session.commit() print 'Inserted user with openid=%s into ESGF database' % openid finally: session.close() else: print 'User with openid: %s already existing in ESGF database, no action taken' % esgfUser.openid pass
def updatePassword(self, user, clearTextPwd): '''Updates the user password in the ESGF database.''' for openid in user.profile.openids(): # openid must match the configured ESGF host name if settings.ESGF_HOSTNAME in openid: esgfUser = self.getUserByOpenid(openid) if esgfUser is not None: session = self.Session() encPasword = md5_crypt.encrypt(clearTextPwd) esgfUser.password = encPasword print 'Updated ESGF password for user with openid: %s' % openid session.add(esgfUser) session.commit() session.close()
def on_post(self, req, resp): username = req.get_param('username') password = req.get_param('password') info = req.get_param('info') if (username == None or password == None): doc = { 'You did not enter a valid username and password please try again' } else: passhash = md5_crypt.encrypt(password) cursor.execute('''INSERT INTO users(username, password, info, sessiontoken) VALUES(?,?,?,'')''', (username, passhash, info)) db.commit() doc = { 'Updated' } resp.body = json.dumps(doc, cls=SetEncoder) webbrowser.open('signon.html')
def signin(self, user, password, data): salt = self.load("https://webshare.cz/api/salt/", post={'username_or_email': user, 'wst' : ""}) if "<status>OK</status>" not in salt: self.fail_login() salt = re.search('<salt>(.+)</salt>', salt).group(1) password = hashlib.sha1(md5_crypt.encrypt(password, salt=salt)).hexdigest() digest = hashlib.md5(user + ":Webshare:" + password).hexdigest() login = self.load("https://webshare.cz/api/login/", post={'digest' : digest, 'keep_logged_in' : 1, 'password' : password, 'username_or_email': user, 'wst' : ""}) if "<status>OK</status>" not in login: self.fail_login() data['wst'] = re.search('<token>(.+)</token>', login).group(1)
def test_check_and_update_persist(self): """ When a password is compared, the hash should update if needed to change the algorithm; and, commit to the database. """ from passlib.hash import md5_crypt obj = self.User() obj.password = Password(md5_crypt.encrypt('b')) self.session.add(obj) self.session.commit() assert obj.password.hash.decode('utf8').startswith('$1$') assert obj.password == 'b' self.session.commit() obj = self.session.query(self.User).get(obj.id) assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$') assert obj.password == 'b'
def run(self): # Read in the users file of usernames and passwords userList = {} f = open('userListv.txt') for user in f: UserPassword = user.split() userList[UserPassword[0]] = UserPassword[1] f.close() print userList # Generate the password hasheds for the shadow file hashedPasswords = {} for user in userList: h = md5_crypt.encrypt(userList[user]) hashedPasswords[user] = h print '{} - {}'.format(user,userList[user]) print '{}:{}'.format(salt, h) # Generate the passwd file homeDir = '/home/eclazalde' shell = '/bin/bash' userInfo = 'Generated user' uid = 1001 pwFile = open('passwd', 'w') for user in userList: line = ('{}:{}:{}:{}:{}:{}:{}\n').format(user, 'x', uid, uid, userInfo, homeDir, shell) pwFile.write(line) uid += 1 # Generate the shadow file endString = '14538:0:99999:7:::' shFile = open('shadow', 'w') for user in hashedPasswords: line = ('{}:{}:{}\n').format(user, hashedPasswords[user], endString) shFile.write(line)
def type5_decrypt(enc_pwd, dict): print("[*] Bruteforcing 'type 5' hash...\n") # Count passwords in the wordlist passnum = linecounter(dict) print("\tFound %d passwords to test." % passnum) try: passf = open(dict, 'rb') except IOError: print('[ERR] Cannot open:', dict) exit(-1) # Splitting hash split_pwd = enc_pwd.split('$') print("\tTesting: %s" % enc_pwd) if split_pwd[1] == '1': print("\tHash Type = MD5") else: print("\t[ERR] Your 'type 5' hash is not valid.") exit(-1) print("\tSalt = %s" % split_pwd[2]) print("\tHash = %s\n" % split_pwd[3]) count = 0 for line in passf.readlines(): # random status if random.randint(1, 100) == 42: print("\t[Status] %d/%d password tested..." % (count, passnum)) if md5_crypt.encrypt(line.rstrip(), salt=split_pwd[2]) == enc_pwd: print("\n[*] Password Found = %s" % line.decode("utf-8") ) exit(0) count += 1 print("\t[-] Password Not Found. You should try another dictionary.")
if len(argv) > 1: password = argv[1] else: password = getpass('Enter a new root password: '******'Confirm password: '******'Password must be at least 8 characters long.' exit(-1) # Generate random salt and create (TODO: use sha512 with libpam) sha512 hash. password_h = md5_crypt.encrypt(password) # NOT sha512 with open('files/etc/shadow', 'r') as f: lines = f.readlines() root_ent = [i for i, line in enumerate(lines) if 'root' in line] for i in root_ent: old_ent = lines[i].split(':') old_ent[1] = password_h old_ent[2] = '16464' old_ent[3] = '0' lines[i] = ':'.join(old_ent) with open('files/etc/shadow', 'w') as f: print 'Updating shadow file (files/etc/shadow)...' f.writelines(lines)
def hash_password(self, user_name, password, salt): """Creates password hash used by Webshare API""" password = hashlib.sha1(md5_crypt.encrypt(password, salt=salt).encode('utf-8')).hexdigest() digest = hashlib.md5((user_name + ':Webshare:' + password).encode('utf-8')).hexdigest() return password, digest
def rootpass(self, rootpass): from passlib.hash import md5_crypt return self.api().vps_rootpass(domname=escape(self.name), newpasshash=md5_crypt.encrypt(rootpass))
def helper(): hash = md5_crypt.encrypt(SECRET) md5_crypt.verify(SECRET, hash) md5_crypt.verify(OTHER, hash)
def create_user(username, email, password): details = db_details() hash = md5_crypt.encrypt(password) with DBcm.UseDatabase(details) as cursor: _SQL = "insert into users (username, email, password) values (%s, %s, %s)" cursor.execute(_SQL, (username, email, hash,))
def getAuthChallenge(self, publicKey): self.auth_public_key = sanitize_key(publicKey) self.auth_public_key_hash = md5_crypt.encrypt(self.auth_public_key, salt='').encode('base64') self.auth_complete = False return crypto.encrypt_rsa(self.auth_challenge, crypto.load_public_key(publicKey)).encode('base64')
def add_user(cls, username, password): hashed_password = md5_crypt.encrypt(password) user = User(username=username, password=hashed_password) user.save() return user.to_dict()
def createMD5Hash(plainPassword): return md5_crypt.encrypt(plainPassword)
def get_access_token(self): return md5_crypt.encrypt(self.data['password'])
# coding=utf-8 # pip install passlib # http://pythonhosted.org/passlib/genindex.html from passlib.hash import md5_crypt, sha256_crypt, sha512_crypt, sha1_crypt password = '******' sha1 = sha1_crypt.encrypt(password) md5 = md5_crypt.encrypt(password) # /etc/shadow sha256 = sha256_crypt.encrypt(password) sha512 = sha512_crypt.encrypt(password) print(md5,sha256,sha512,sha1) md5_crypt.verify(password, md5) # 验证password和hash值
def verify_access_token(self, access_token): return md5_crypt.verify(access_token, md5_crypt.encrypt(self.data['password']))
def _encrypt(self, clearvalue, salt=None): return md5_crypt.encrypt(clearvalue)
def pw_hash(pw_plain): # return = hashlib.md5(pw_plain).hexdigest() return md5_crypt.encrypt(pw_plain)
def secret5(self, clear_secret): """ take clear_secret and return a cisco level5 hash """ return md5_crypt.encrypt(clear_secret)