严格来说:base64 和md5都不是加密算法。因为没有密钥。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
===========================
# @Time : 2020/9/3 11:47
# @File : MD5_.py
# @Author: adeng
# @Date : 2020/9/3
============================
"""
import hashlib
# 01 MD5加密
name = "阿登"
# unicode 转码成 utf8
name = name.encode("utf-8")
# 或者
# bytes(name,encoding="utf-8")
# 实例化md5加密算法对象
md5 = hashlib.md5()
md5.update(name) # name 这里字符串必须是bytes
print(md5.hexdigest()) # hexdigest() 十六进制显示
print(md5.digest()) # digest()是将加密结果以二进制显示
# 封装成一个函数
def md5_16(x:str) ->str:
"""
return: 16进制显示结果
"""
import hashlib
md5 = hashlib.md5(x.encode("utf-8"))
return md5.hexdigest()
def md5_2(x:str) ->str:
"""
return: 二进制显示结果
"""
import hashlib
md5 = hashlib.md5(x.encode("utf-8"))
return md5.digest()
md5_16("罗罗女神") # 2d18f116f57e1ee19588a791b2def832
md5_2("罗罗小姐姐") # b'-\x18\xf1\x16\xf5~\x1e\xe1\x95\x88\xa7\x91\xb2\xde\xf82'
#--------------------------------------------------------------------#
# 02 base64加密
import base64
# -------开发做的加密过程------
# 1.需要加密的字符串,必须是bytes.纯英文可以这种形式:b'纯英文'
s = "阿登小哥哥"
# s = "阿登小哥哥".encode("utf-8")
# 2. 进行加密,返回一个加密后的对象
base_s = base64.b64encode(s.encode("utf-8"))
print(base_s) # b'6Zi/55m75bCP5ZOl5ZOl'
def base64_str(x):
import base64
return base64.b64encode(x.encode())
base64_str("乔木小姐姐") # b'6Zi/55m75bCP5ZOl5ZOl'
# -----base64 解密过程
base_str = base64_str("乔木小姐姐")
b = base64.b64decode(base_str)
b = b.decode()
print(b)
def base64_decode(x):
import base64
return base64.b64decode(x).decode()
base64_decode(b'6Zi/55m75bCP5ZOl5ZOl')
# 03 ----------通过md5,推到其他加密方式基本差不多如:sha1
s1 = "阿登00001"
# sha1 40位 16进制
sha11 = hashlib.sha1()
sha11.update(s1.encode())
print(sha11.hexdigest()) # a5e274c0332ef484ec64b3fedc03cd57a0172afc
print(len(sha11.hexdigest()))
# sha256 64位 16进制。
sha256 = hashlib.sha256()
sha256.update(s1.encode())
print(sha256.hexdigest()) # ab52041a93da347330a3c7b366192f0281cae7e7f46aa399dc174b14729911b8
print(len(sha256.hexdigest()))
# sha256 128位 16进制。
sha512 = hashlib.sha512()
sha512.update(s1.encode())
print(sha512.hexdigest()) # 1c624ba2b0b55c3fbeaddbd7355af12352a54564f1a284c2afc157dbe70e419bd5b1cc5032e2aa6ab687812510ae59b92198a1c04bbae93cccc4a9b8a7ea2b86
print(len(sha512.hexdigest()))
# ============ 场景 注册---》登录 -------------
"""
本xx.py文件相对路径 有1个db.txt,请事先建好。内容如下:
db.txt
adeng:6389facfcc60a2eb00f7a588ca873a02:admin
adeng1:6389facfcc60a2eb00f7a588ca873a02:admin
xiangjia:6389facfcc60a2eb00f7a588ca873a02:user
"""
# 判断用户是否在数据表,这里我用db.txt模拟
def user_is_exist(username):
with open("db.txt", mode="rt", encoding="utf-8") as f1:
for line in f1:
user, pwd1, role = line.strip().split(":")
if username == user:
print(f'[{username}]用户已注册')
return False
print(f'[{username}]用户未注册')
return True
# 判断密码长度是否在 [6,12]
def pwd_in_range(password):
if 6 <= len(password) <= 12:
return True
else:
if len(password) < 6:
print("密码长度小于6位")
else:
print("密码长度大于12位")
return False
#阶段1: 接收用户输入账号与密码,完成合法性校验
def talk():
while True:
username = input('请输入你的用户名: ').strip()
if username.isalpha() and user_is_exist(username):
break
else:
print('用户必须为字母')
while True:
password1 = input('请输入你的密码: ').strip()
password2 = input('请再次输入你的密码: ').strip()
if password1 == password2 and pwd_in_range(password1):
break
else:
print('输入密码要么两次不一致,要么长度不在【6--12】')
role_dic = {
'1': 'user',
'2': 'admin'
}
while True:
for k in role_dic:
print(k, role_dic[k])
choice = input('请输入您的身份>>: ').strip()
if choice not in role_dic:
print('输入的身份不存在')
continue
else:
role = role_dic[choice]
break
return username, password1, role
# 阶段2: 将账号密码拼成固定的格式
def register_interface(username, password, role):
# 调用上面封装的md5_16()方法进行加密
password = md5_16(password)
format_str = '%s:%s:%s\n' % (username, password, role)
return format_str
# 阶段3: 将拼好的格式写入文件
def handle_file(format_str, filepath):
with open(r'%s' % filepath, 'at', encoding='utf-8') as f:
f.write(format_str)
def register():
user, pwd, role = talk()
format_str = register_interface(user, pwd, role)
handle_file(format_str, 'db.txt')
def login():
inp_name = input("输入你的用户名:").strip()
inp_pwd = input("输入你的密码:").strip()
# 加密 pwd
inp_pwd = md5_16(inp_pwd)
with open(r"db.txt",mode="rt", encoding="utf-8") as f:
for line in f :
user,pwd,role = line.strip("\n").split(":")
if user ==inp_name and pwd == inp_pwd:
print("登录成功")
break
else:
print("账号或者用户名输入错误")
register()
login()
# ------------------------------++++++++++++++++++-----------------------------
# 上面封装的md5_16()方法,还是有可能被逆转的,我们多传1个key
def md5_16(x:str,key="dyunren") ->str:
"""
return: 16进制显示结果
"""
import hashlib
x = x +key
md5 = hashlib.md5(x.encode("utf-8"))
return md5.hexdigest()
print(md5_16("fsafafa110"))
md5 封装加一个key,提高安全性
# 上面封装的md5_16()方法,还是有可能被逆转的,我们多传1个key
def md5_16(x:str,key="dyunren") ->str:
"""
return: 16进制显示结果
"""
import hashlib
x = x +key
md5 = hashlib.md5(x.encode("utf-8"))
return md5.hexdigest()
print(md5_16("fsafafa110"))
对文件进行md5加密
#-------文件内容进行加密---------需要获取文件的内容,即可-------
"""
adeng.txt 的内容是:
阿登好帅啊
"""
def md5_file(path):
import hashlib,os
if not os.path.isfile(path):
raise TypeError(f"{path} 不是一个文件")
with open(path,mode="rb") as f:
md5 = hashlib.md5()
for line in f:
md5.update(line)
return md5.hexdigest()
print(md5_file("adeng.txt"))
网友评论