您的位置:首页 > 编程语言 > Python开发

python-常用模块xml、shelve、configparser、hashlib

2018-08-13 17:01 666 查看

一、shelve模块

shelve模块也是用来序列化的.

使用方法:

  1.open

  2.读写

  3.close

import configparser

config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8')

#删除整个标题section2
config.remove_section('section2')

#删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')

#判断是否存在某个标题
print(config.has_section('section1'))

#判断标题section1下是否有user
print(config.has_option('section1',''))

#添加一个标题
config.add_section('egon')

#在标题egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #报错,必须是字符串

#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
View Code

模拟一个下载功能 最大连接速度可以由用户来控制,用户不能看代码,所以提供一个配置文件

import configparser

cfg = configparser.ConfigParser()
cfg.read("download.ini")
print(cfg.sections())
print(cfg.options("section1"))

print(type(cfg.get("section1","maxspeed")))
print(cfg.get("section1","maxspeed"))

print(cfg.getint("section2","minspeed"))

#修改最大速度为2048
cfg.set("section1","maxspeed","2048")

cfg.write(open("download.ini","w",encoding="utf-8"))

四、hashlib模块

hash是一种算法,用于将任意长度的数据,压缩映射到一段固定长度的字符(提取特征)常用于加密和文件校验

hash值的特点:

  1.传入值不同,得到的hash值有可能相同

  2.不能由hash值返解成内容

  3.只要hash算法不变,无论输入的数据长度是多少,得到的hash值长度相等

破解MD5的方法可以尝试撞库,原理:有一个数据库中存放了常见的明文和密文的对应关系,可以拿密文去查数据库里已经存在的明文,如果有就是撞库成功,能不能破解全凭运气

import hashlib
md = hashlib.md5()
md.update("123456".encode("utf-8"))
print(md.hexdigest())

常用的提升安全性的手段就是加盐

md2 = hashlib.md5()
md2.update("123".encode("utf-8"))
md2.update(pwd.encode("utf-8"))
md2.update("231".encode("utf-8"))
print(md2.hexdigest())

还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密,不加盐会报错

hmac模块的使用步骤与hashlib模块的使用步骤基本一致,只是在第1步获取hmac对象时,只能使用hmac.new()函数,因为hmac模块没有提供与具体哈希算法对应的函数来获取hmac对象。

import hmac

h = hmac.new(b"net")
h.update(b"luzhuo.me")
h_str = h.hexdigest()
print(h_str)

 补充:

hash.digest()
 
返回摘要,作为二进制数据字符串值

hash.hexdigest()
 
返回摘要,作为十六进制数据字符串值

 

 

每天都学习!!!!!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: