Python hmac模块使用实例解析
这篇文章主要介绍了Pythonhmac模块使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
hmac模块的作用:
用于验证信息的完整性。
1、hmac消息签名(默认使用MD5加算法)
hmac_md5.py
#!/usr/bin/envpython #-*-coding:utf-8-*- importhmac #默认使用是md5算法 digest_maker=hmac.new('secret-shared-key'.encode('utf-8')) withopen('content.txt','rb')asf: whileTrue: block=f.read(1024) ifnotblock: break digest_maker.update(block) digest=digest_maker.hexdigest() print(digest)
content.txt
Loremipsumdolorsitamet,consectetueradipiscingelit.Donec egestas,enimetconsectetuerullamcorper,lectusligularutrumleo,a elementumelittortoreuquam.Duistinciduntnisiutante.Nulla facilisi.Sedtristiqueeroseulibero.Pellentesquevelarcu.Vivamus purusorci,iaculisac,suscipitsitamet,pulvinareu, lacus.Praesentplacerattortorsednisl.Nuncblanditdiamegestas dui.Pellentesquehabitantmorbitristiquesenectusetnetuset malesuadafamesacturpisegestas.Aliquamviverrafringilla leo.Nullafeugiataugueeleifendnulla.Vivamusmauris.Vivamussed maurisinnibhplacerategestas.Suspendissepotenti.Maurismassa.Ut egetvelitauctortortorblanditsollicitudin.Suspendisseimperdiet justo.
运行效果
[root@mnt]#python3hmac_md5.py 79cbf5942e8f67be558bc28610c02117
2、hmac消息签名摘要(使用SHA1加算法)
hmac_sha1.py
#!/usr/bin/envpython #-*-coding:utf-8-*- importhmac digest_maker=hmac.new('secret-shared-key'.encode('utf-8'),b'',digestmod='sha1') #hmac.new(key,msg,digestmod) #key:加盐的key, #msg:加密的内容, #digestmod:加密的方式 withopen('hmac_sha1.py','rb')asf: whileTrue: block=f.read(1024) ifnotblock: break digest_maker.update(block) digest=digest_maker.hexdigest() print(digest)
运行效果
[root@mnt]#python3hmac_sha1.py e5c012eac5fa76a274f77ee678e6cc98cad8fff9
3、hmac二进制消息签名摘要(使用SHA1加算法)
hmac_base64.py
#!/usr/bin/envpython #-*-coding:utf-8-*- importhmac importbase64 importhashlib withopen('test.py','rb')asf: body=f.read() #默认使用是md5算法 digest_maker=hmac.new('secret-shared-key'.encode('utf-8'),body,hashlib.sha1) #hmac.new(key,msg,digestmod) #key:加盐的key, #msg:加密的内容, #digestmod:加密的方式 digest=digest_maker.digest()#默认内容是字节类型,所以需要base64 print(base64.encodebytes(digest))#注意base64结果是以\n结束,所以Http头部或其它传输时,需要去除\n
运行效果
[root@mnt]#python3hmac_base64.py b'Y9a4OMRqU4DB6Ks/hGfru+MNXAw=\n'
4、hmac摘要数据比较示例
hmac_pickle.py
#!/usr/bin/envpython #-*-coding:utf-8-*- importhashlib importhmac importio importpickle defmake_digest(message): "返消息摘要,加密码后的结果" hash=hmac.new( 'secret-shared-key'.encode('utf-8'), message, hashlib.sha1 ) returnhash.hexdigest().encode('utf-8') classSimpleObject(object): def__init__(self,name): self.name=name def__str__(self): returnself.name #输出缓冲区 out_s=io.BytesIO() o=SimpleObject('digestmatches') pickle_data=pickle.dumps(o)#序列化 digest=make_digest(pickle_data)#使用sha1加密算法 header=b'%s%d\n'%(digest,len(pickle_data)) print('提示:{}'.format(header)) out_s.write(header)#将消息头写入缓冲区 out_s.write(pickle_data)#将序列化内容写入缓冲区 o=SimpleObject('digestdoesnotmatches') pickle_data=pickle.dumps(o) digest=make_digest(b'notthepickleddataatall') header=b'%s%d\n'%(digest,len(pickle_data)) print('提示:{}'.format(header)) out_s.write(header)#将消息头写入缓冲区 out_s.write(pickle_data)#将序列化内容写入缓冲区 out_s.flush()#刷新缓冲区 #输入缓冲区 in_s=io.BytesIO(out_s.getvalue()) whileTrue: first_line=in_s.readline() ifnotfirst_line: break incoming_digest,incoming_length=first_line.split(b'') incoming_length=int(incoming_length.decode('utf-8')) print('读取到:',incoming_digest,incoming_length) incoming_pickled_data=in_s.read(incoming_length) actual_digest=make_digest(incoming_pickled_data)#实际的摘要 print('实际值:',actual_digest) ifhmac.compare_digest(actual_digest,incoming_digest):#比较两个摘要是否相等 obj=pickle.loads(incoming_pickled_data) print('OK:',obj) else: print('数据不完整')
运行效果
[root@mnt]#python3hmac_pickle.py 提示:b'00e080735a8de379e19fe2aa731c92fc9253a6e269\n' 提示:b'1d147690f94ea374f6f8c3767bd5a5f9a8989a5378\n' 读取到:b'00e080735a8de379e19fe2aa731c92fc9253a6e2'69 实际值:b'00e080735a8de379e19fe2aa731c92fc9253a6e2' OK:digestmatches 读取到:b'1d147690f94ea374f6f8c3767bd5a5f9a8989a53'78 实际值:b'4dcaad9b05bbb67b571a64defa52e8960a27c45d' 数据不完整
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。