五、python中的MD5加密介绍

import hashlib

'''
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
'''
##############MD5#################
def func_MD5(string):
    hash=hashlib.md5()
    hash.update(string)
    m=hash.hexdigest()
    print (m)
func_MD5("123")

######## sha1 #####################
def func_sha1(string):
    hash = hashlib.sha1()
    hash.update(bytes(string))
    print(hash.hexdigest())
func_sha1("123")
# ######## sha256 ########
def func_sha256(string):
    hash = hashlib.sha256()
    hash.update(bytes(string))
    print(hash.hexdigest())
func_sha256("123")
# ######## sha384 ########
def func_sha384(string):
    hash = hashlib.sha384()
    hash.update(bytes(string))
    print(hash.hexdigest())
func_sha384("123")
# ######## sha512 ########
def func_sha512(string):
    hash = hashlib.sha512()
    hash.update(bytes(string))
    print(hash.hexdigest())

func_sha512("123")
'''
以上加密算法虽然厉害,但存在缺陷,可通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
'''

def func_MD5_deep(string):
    hash=hashlib.md5(bytes("sdfgdfsgsdf"))    #key加密
    hash.update(string)
    m=hash.hexdigest()
    print(m)

func_MD5_deep("123")
-----------------------------------------------------------------

   202cb962ac59075b964b07152d234b70
   40bd001563085fc35165329ea1ff5c5ecbdbbeef
   a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3
   9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f
   3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2
   066290ee749d0cc66116a3f55ecc241c

-----------------------------------------------------------------
'''
练习题:注册登录加密函数
'''
def fun_md5(arg):
    hash=hashlib.md5(bytes("1232..gg"))
    hash.update(arg)
    m=hash.hexdigest()
    return m

def register(user2,pwd2):
    with open("denglu.db","wb") as f:
        temp=user2+"|"+fun_md5(pwd2)
        f.write(temp)
def login(user1,pwd1):
    with open("denglu.db","r") as f:
        for line in f:
            a,b=line.strip().split("|")
            if user1==a and fun_md5(pwd1)==b:
                print("登录成功!")
            else:
                print("用户名和密码不匹配!")
def func():
    temp=input("1:登录,2注册")
    if temp==1:
        user = raw_input("请输入用户名:")
        pwd = raw_input("请输入密码:")
        login(user,pwd)
    else:
        user = raw_input("请输入用户名:")
        pwd = raw_input("请输入密码:")
        register(user,pwd)

func()

你可能感兴趣的:(python)