模块篇:hashlib加密模块、logging日志模块

2022.3.31加密模块与日志模块

qfRVpV.md.jpg

  • hashlib加密模块
  • logging日志模块

一、hashlib加密模块

1、什么是加密

将人能看得懂的数据经过一些手段变成看不懂的数据,即明文变成密文,密文的表现形式一般都是一串没有规则的字符串

2、加密算法

加密算法有很多种(就是将明文变密文的内部规则)

算法的难易程度可以根据产生密文的长短来判断,越长则越复杂

3、什么时候使用加密

涉及到隐私数据的时候,应该考虑使用加密,最为常见的就是对用户的密码加密,防止密码泄露

4、基本使用

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
import hashlib 1.指定算法>>>md5算法 md5 = hashlib.md5() 2.将明文数据传递给算法对象 md5.update(b'hello') # 只能接收bytes类型 # 这里如果字符串中是纯数字和英文,那么直接在前面加b或转成bytes类型 3.获取加密后的密文数据 res = md5.hexdigest() # res即为加密后的密文数据,获取便于比对数据 注意:在传入数据时,若传入内容一致,那么算法的结果肯定一致

5、加密补充

(1)加密之后是无法反解密的

所谓的反解密其实是暴力破解>>>反复猜

(2)加盐处理

由于防止一些暴力破解的出现,可以给密码增加难度,即增加一些额外的干扰项

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
import hashlib md5 = hashlib.md5() md5.update('hello'.encode('utf8')) # 增加干扰项 md5.update(b'123') print(md5.hexdigest())

(3)动态加盐

即干扰项是动态变化的,可以使用用户名的一部分,也可以使用当前时间等

6、加密应用场景

(1)密码加密如何比对

用户输入明文>>>相同算法转化成密文>>>和数据库中密文比对

(2)文件一致性校验

作为软件的提供者,我们在提供软件的同时会给该软件内容做加密处理,得到一个该软件的密文,用户在获取到软件后也会对内容做相同的加密,之后比对密文是否一致

如果一致则中途没有修改,若不一致则表示中途被修改过,可能存在病毒

如果一个文件有10G,或者很大,全部读取并加密势必速度会很慢,这时候可以考虑对文件内容进行切片读取并加密的操作

二、logging模块

即日志模块,就是在程序的各个环境记录,便于后续的查看

1、日志等级

日志按照重要程度分为五个级别:默认只有达到warning警告级别及以上才会记录日志

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')

2、基本使用

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
import logging file_handler =logging.FileHandler(filename='x1.log', mode='a', encoding='utf8') logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', handlers=[file_handler, ], level=logging.ERROR ) logging.error('赶紧好好学习!')

三、昨日作业

作业完成心得:

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
今天写编程作业的时候,一开始注册登录思路都比较清晰,但是到了添加购物车的环节就出现很多问题,但是好的一方面是不会出现像昨天那样不会处理路径的基础问题,但是今天的作业还是没能够独立完成,因为在写到购物车的时候,没有想到使用临时购物车的方法,而是想直接修改文件中的内容,这样会导致程序比较繁杂而且没有头绪,所以还是借鉴了老师的思路,我觉得这种思路需要好好去培养,一个编程的框架一开始就要大致理好,当然在出现问题的时候也可以及时调整。 总的来说,今天写的编程有几个需要注意的点: 1.自己要直到自己存入数据的字典大概长什么样,不然很难去调用 2.加密密码需要使用二进制,不然会有隐患 3.在思路混乱时需要重新理思路,有一个重点,在获取用户输入的时候就要想到用户输入的多种情况,需要怎么分支 4.在获取完用户输入之后,需要使用哪些变量来计算或者存储,在所有情况考虑完之后,记得使用变量把需要处理的数据进行整合,方便后面存储和计算 5.一些基础问题,考虑好是不是需要分支,还有代码的前后顺序不一样会有什么影响,都需要考虑到位 今天只是将昨天没有写好的作业重新写了一下,不过也使用的今天学习的MD5加密算法模块,感觉非常有趣。当然我也很有感触,因为这也是第一次让自己觉得有很大挑战性,不过我不会灰心,也不会觉得自己是小白就理所应当。

代码实战篇

要求:重新写昨日作业,并且针对用户的密码可以采用加密模块实现

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
''' # 项目功能 1.用户注册 2.用户登录 3.添加购物车 4.结算购物车 # 项目说明 用户数据采用json格式存储到文件目录db下 一个用户一个单独的文件 数据格式 {"name":"jason","pwd":123} # ps:文件名可以直接用用户名便于校验 用户注册时给每个用户添加两个默认的键值对(账户余额 购物车) {"balance":15000,"shop_car":{}} 添加购物车功能 商品列表可以自定义或者采用下列格式 good_list = [ ['挂壁面',3], ['印度飞饼', 22], ['极品木瓜', 666], ['土耳其土豆', 999], ['伊拉克拌面', 1000], ['董卓戏张飞公仔', 2000], ['仿真玩偶', 10000] ] 用户可以反复添加商品,在购物车中记录数量 {'极品木瓜':[个数,单价]} 结算购物车 获取用户购物车中所有的商品计算总价并结算即可 # 思考:针对添加购物车和结算只有登录的用户才可以执行如何实现 ''' import json import os import hashlib this_path = os.path.dirname(__file__) data_path = os.path.join(this_path, 'db') if not os.path.exists(data_path): os.mkdir(r'db') is_login = {'username':None} def register(): user_name = input('输入用户名注册>>>:').strip() pass_word = input('输入注册密码>>>:').strip() md5 = hashlib.md5() md5.update(pass_word.encode('utf8')) pass_word = md5.hexdigest() user_dict = {'name': user_name, 'pwd': pass_word, "balance": 15000, "shop_car": {}} file_path = os.path.join(data_path, f'{user_name}.json') res = os.listdir(data_path) for i in res: if user_name == i: print('用户已存在,无需注册!') return with open(file_path, 'a', encoding='utf8') as f: json.dump(user_dict, f, ensure_ascii=False) print('注册成功!') def login(): user_name = input('请输入用户名登录>>>:') pass_word = input('请输入登录密码>>>:') file_path = os.path.join(data_path,f'{user_name}.json') if not os.path.exists(file_path): print('请先注册再登录!') return with open(file_path,'r',encoding='utf8') as f: user_dict = json.load(f) md5 = hashlib.md5() md5.update(pass_word.encode('utf8')) pass_word = md5.hexdigest() if not user_dict['pwd'] == pass_word: print('密码错误!') return print(f'欢迎{user_name}登录!') is_login['username'] = user_name from functools import wraps def check_log(func): @wraps(func) def inner(*args,**kwargs): if is_login['username']: res = func(*args,**kwargs) return res else: print('需要先登录!') return inner @check_log def add(): good_list = [ ['挂壁面', 3], ['印度飞饼', 22], ['极品木瓜', 666], ['土耳其土豆', 999], ['伊拉克拌面', 1000], ['董卓戏张飞公仔', 2000], ['仿真玩偶', 10000] ] user_shop_car = {} # 创建一个临时购物车 while True: for i,j in enumerate(good_list): print(f'商品编号:{i} |商品名称:{j[0]} |商品单价:{j[1]}') choice = input('请输入想要的商品编号或者输入y退出添加>>>:').strip() # 获取用户输入编号 file_path = os.path.join(data_path, f"{is_login['username']}.json") if choice == 'y': # 将添加好的购物车放入临时购物车 with open(file_path, 'r',encoding='utf8') as f: # 打开真实购物车 real_user_dict = json.load(f) real_shop_car = real_user_dict['shop_car'] for i in user_shop_car: if i in real_shop_car: real_shop_car[i][1] += user_shop_car[i][1] continue else: real_shop_car[i] = user_shop_car[i] with open(file_path, 'w',encoding='utf8') as f: json.dump(real_user_dict,f,ensure_ascii=False) print('商品添加成功!') break if not choice.isdigit(): # 判断是否是数字 print('请输入正确的商品编号!!!') continue choice = int(choice) # 转为整型,方便后面取值 if not choice in range(len(good_list)): # 判断用户输入的编号在不在商品列表 print('该商品不在范围内,请重新输入!') continue # 获取用户选好的商品 target_shop = good_list[choice][0] # 因为商品编号是以索引值命名,所以各异取到 target_price = good_list[choice][1] choice2 = input('请输入需要购买的个数>>>').strip() if not choice2.isdigit(): print('请输入数字!!!') continue choice2 = int(choice2) if target_shop in user_shop_car: user_shop_car[target_shop][1] += choice2 else: user_shop_car[target_shop] = [target_price, choice2] @check_log def bill(): # 拼接路径 file_path = os.path.join(data_path, f"{is_login['username']}.json") with open(file_path,'r',encoding='utf8') as f: # 获取购物车信息 user_shop_dict = json.load(f) real_shop_car = user_shop_dict['shop_car'] balance = user_shop_dict['balance'] # 设置一个初始金额 first_money = 0 # 计算价格 for i in real_shop_car: first_money += real_shop_car[i][0] * real_shop_car[i][1] # 结算购物车,判断用户余额是否充足 if first_money <= balance: balance -= first_money # 写入文件 with open(file_path, 'w', encoding='utf8') as f: json.dump(user_shop_dict,f,ensure_ascii=False) print('结算成功,欢迎下次光临!!!') return else: print('不好意思,余额不足!!!') func_dict = {'1':register,'2':login,'3':add,'4':bill} while True: print(''' 1.用户注册 2.用户登录 3.添加购物车 4.结算购物车 5.退出 ''') choice = input('请输入功能编号>>>:').strip() if choice in func_dict: func_dict[choice]() elif choice == '5': break else: print('请输入正确的功能编号!')
posted @   马氵寿  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开