python2.7下面字节数组(ByteArray)和16进制字符串(HexString)转化

来源:互联网 发布:网络技术培训机构 编辑:程序博客网 时间:2024/06/06 06:57

由于是python2.7 

严谨起见,文中不使用字符串的说法,下面只使用str或者unicode的说法


之所以有这个需要,是因为:

Hmac-sha1加密在网上计算的结果是HexString,也就是16进制字符串

而在python中的计算结果是ByteArray,两者结果不同,于是就萌生了两者如何转化的疑问.

由于python2.7中没有Bytes

py2没有bytes的概念 所以把字节数组当成str输出了


下面是互相转化的方法:

# coding: utf-8#在线计算链接http://tool.oschina.net/encrypt?type=2#用来加密的字符串:csdmniojfw98nvdico#需要输入的秘钥:214fdsf23dcimport hmacimport hashlibimport base64import hashlibdef hmac_sha1(app_secret,base_result):    result=hmac.new(app_secret,base_result, hashlib.sha1).digest()    l=['{:02X}'.format(ord(i)) for i in result]    s=''.join(l)    print"以上是从python结果转化为在线计算结果,也就是从字节数组转化为16进制数组"    news=bytearray.fromhex(s)    print"以上是从在线计算结果转化为python结果,也就是从16进制数组转化为字节数组"    print "s=",s    print "news=",news                            return resultif __name__ == '__main__':    app_secret='214fdsf23dc'    base_result='csdmniojfw98nvdico'    result=hmac_sha1(app_secret,base_result)    print "result=",result






阅读全文
0 0
原创粉丝点击