散列在python中(加密)

时间:2014-05-03 22:40:59

标签: python encryption hash passwords

我正在尝试对我的登录程序实施加密,我在许多地方都寻求帮助,但我似乎无法理解其中任何一项。 我是一个相当新的python,我正在为它的大学课程做准备。 我很感兴趣,如果有可能将它作为一个类在我已经解决的程序中实现,任何提示或解释将不胜感激

基本上我要问的是,如果我希望程序在运行之间加密密码并再次解密它们,以便程序在运行时可以使用它们,它会怎么样?

程序:

import json 

with open("login_data.txt", "r") as login_file:
    try:
        users = json.load(login_file)
    except:
        users = {}

status = ""

def Display_Menu():

    status = input("Are you a registered user? (y/n)? Press q to quit: ")
    if status == "y":
        Old_User()
    elif status == "n":
        New_User()
    elif status == "passwd":
        Change_Passwd()
    elif status == "q":
        skriva = open("login_data.txt", "w")
        json.dump(users, skriva)
    return status

def New_User():

    Create_Login =input("Create login name: ")
    if Create_Login in users:
        print ("Login name already exist!")
    else:
        Create_Password =input("Create password: ")
        users[Create_Login] = Create_Password
        print("New User created!")        
    current_user = None

def Old_User():
    global current_user  

    login =input("Enter login name: ")
    Password =input("Enter password: ")

    if login in users and users[login] == Password:

        print("Login successful!")  
        current_user = login
        status = input("Wanna quit, change pass, och logout?")       
        if status == "passwd":
            Change_Passwd()
        elif status == "logout":
            Display_Menu()
        elif status == "q":
            skriva = open("login_data.txt", "w")
            json.dump(users, skriva)
        return status

    else:
        print("User doesn't exist or wrong password!")

def Change_Passwd():    
    oldpass =input("Old password: ")

    if current_user in users and users[current_user] == oldpass:
        Create_Password = input("New password: ")
        users[current_user] = Create_Password

        if Create_Password == input("Confirm password: "):
            print("Password changed!")
        else:
            print("User authorization failure")
            users[current_user] = oldpass
    else:
        print ("No password match!")

while status != "q":            
    status = Display_Menu()

2 个答案:

答案 0 :(得分:0)

MD5是一种非常简单的哈希算法,这是一些示例用法:

>>> hashlib.md5("String you want to encrypt").hexdigest()
'096a773d70e934d03ae3dd8022deed5e'

MD5绝不是安全的,但它足以说明一些观点。例如,您可以以您选择的某种格式存储用户名和散列密码,即:

username1, hash1
username2, hash2

这(Difference between Hashing a Password and Encrypting it)可能是一个相关的阅读。

答案 1 :(得分:0)

bcrypt是一个你应该看看的图书馆。

import bcrypt
password = b"super secret password"
# Hash a password for the first time, with a randomly-generated salt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Check that a unhashed password matches one that has previously been
#   hashed
if bcrypt.hashpw(password, hashed) == hashed:
    print("It Matches!")
else:
    print("It Does not Match :(")