Python hashlib

hashlib: セキュアハッシュやメッセージダイジェスト用の様々なアルゴリズムを実装。sha256は有名ですよね。
e.x. sha1, sha224, sha256, sha384, sha512, RSA md5

コンストラクタがあり、ハッシュオブジェクトを返す

import hashlib 
m = hashlib.sha256()
m.update(b"National Security Agency")
print(m.digest())

print(m.digest_size)
print(m.block_size)

[vagrant@localhost python]$ python main.py
b’t\xc6!\xc4\xd2\xd3W&r4\xa2\xe2\xa9\x1f\x15k\xb9\xf1\x08\xa9\x10\xb6\xd2\xb5\xe6\x05|\xe2d\x81\xc8\xe6′
32
64

sha224で実行すると
b’\xe9\xf0\xee\xd4F\xd0;-MM\xa1\xc9\x8cY\x05\x1c\x81H\xde8\x95\x94\x0f\xcb\x13he\x89′

hash.update()でオブジェクトを更新
“b”でエンコード
よく使われるのは、md5とsha256

Blockchain その1

こちらのコードを分解していきます。

import hashlib
import json
import datetime

class Block:
	def __init__(self, index, timestamp, transaction, previous_hash):
		self.index = index 
		self.timestamp = timestamp 
		self.transaction = transaction 
		self.previous_hash = previous_hash 
		self.property_dict = {str(i): j for i, j in self.__dict__.items()}
		self.now_hash = self.calc_hash()

	def calc_hash(self):
		block_string = json.dumps(self.property_dict, sort_keys=True).encode('ascii')
		return hashlib.sha256(block_string).hexdigest()

def new_transaction(sender, recipient, amount):
	transaction = {
		"差出人": sender,
		"宛先": recipient,
		"金額": amount,
	}
	return transaction

block_chain = []
genesis_block = Block(0, 0, 0, "-")
block_chain.append(genesis_block)

transaction = new_transaction("タロウ", "花子", 100)
new_block = Block(1, str(datetime.datetime.now()), transaction, block_chain[0].now_hash)
block_chain.append(new_block)

for key, value in genesis_block.__dict__.items():
	print(key, ':', value)

print("")

for key, value in new_block.__dict__.items():
	print(key, ':', value)

[vagrant@localhost python]$ python app.py
property_dict : {‘transaction’: 0, ‘index’: 0, ‘previous_hash’: ‘-‘, ‘timestamp’: 0}
now_hash : 49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20
transaction : 0
index : 0
previous_hash : –
timestamp : 0

property_dict : {‘transaction’: {‘宛先’: ‘花子’, ‘差出人’: ‘タロウ’, ‘金額’: 100}, ‘index’: 1, ‘previous_hash’: ’49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20′, ‘timestamp’: ‘2019-10-18 10:55:22.499513’}
now_hash : b9b57282d7387add7e66d6209f06e4c132ec01cfece9615067bdffeb7b8f4c30
transaction : {‘宛先’: ‘花子’, ‘差出人’: ‘タロウ’, ‘金額’: 100}
index : 1
previous_hash : 49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20
timestamp : 2019-10-18 10:55:22.499513