python2.7下面字节数组(ByteArray)和16进制字符串(HexString)转化
生活随笔
收集整理的這篇文章主要介紹了
python2.7下面字节数组(ByteArray)和16进制字符串(HexString)转化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
由于是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 #需要輸入的秘鑰:214fdsf23dc import hmac import hashlib import base64 import hashlib def 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=",sprint "news=",news return result if __name__ == '__main__':app_secret='214fdsf23dc'base_result='csdmniojfw98nvdico'result=hmac_sha1(app_secret,base_result)print "result=",result
總結
以上是生活随笔為你收集整理的python2.7下面字节数组(ByteArray)和16进制字符串(HexString)转化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sublime的TAB和空格统一
- 下一篇: sublime支持虚拟环境python2