LoginSignup
7
8

More than 5 years have passed since last update.

Python3での16進のあつかい

Posted at

セキュリティ関連でハッシュなどを使うときに、そのままprintで表示しても文字化けしちゃって読めないので、そこら辺をいろいろいじっていたときのメモ。

str型とbytes型

'test' == b'test'

srt型とbytes型なので、もちろん違うのでFalseが返ってくる。

str->bytesへの変換

'test'.encode('utf-8') == b'test'

strをbytes型へ変換してるのでTrueが返ってくる。

バイナリデータの16進表現を返す

from binascii import hexlify
hexlify(b'A')

「b'41'」が返ってくる。

16進表記の文字列hexstrの表すバイナリデータを返す

from binascii import unhexlify
unhexlify(b'41')

hexlifyの逆なので「b'A'」が返ってくる。

b''を取り外したい

b'A'.decode('utf-8')

上記をふまえてhashを使ってみる

import hashlib

from binascii import hexlify

origin = 'あ'
encoded_origin = origin.encode('utf-8')
hash_obj = hashlib.sha256()
hash_obj.update(encoded_origin)
digest = hash_obj.digest()
print(digest)                 # 人間が読めない
print(hexlify(digest))        # 人間が読める
7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8