天天看點

區塊鍊中 非對稱加密通信的大緻過程

場景:

A要給B發資訊。使用非對稱加密,A的公鑰為A_public, 私鑰為A_private;   B的公鑰為B_public, 私鑰為B_private。

A要發送的資訊為msg。

過程:

1.   A 對要發送的資訊msg求出 hash值(msg_hash),  對求出的 msg_hash 使用A的私鑰加密獲得加密簽名後的hash值為 A_cry_msg_hash。

2.   将  A_cry_msg_hash 與  msg 拼接獲得   A_cry_msg_hash+msg 。

3.   使用  B的公鑰加密簽名   A_cry_msg_hash+msg  獲得   B_cry(A_cry_msg_hash+msg),  并将其發送給B。

4.   B獲得  B_cry(A_cry_msg_hash+msg)  ,使用B的私鑰解密獲得  A_cry_msg_hash+msg  。

5.   B 求出msg的hash值 B_msg_hash   ,  使用A的公鑰解密 A_cry_msg_hash 獲得  msg_hash,  如果 B_msg_hash 等于 msg_hash  則資訊沒有被篡改。

============================================

區塊鍊中 非對稱加密通信的大緻過程
區塊鍊中 非對稱加密通信的大緻過程

圖來自于   《Learn Blockchains by Building One》

======================================================

部分展示代碼:

需要安裝pynacl庫:

pip install pynacl

from nacl.public import PrivateKey, Box

# Generate Bob's private key, which must be kept secret
bobs_secret_key = PrivateKey.generate()
alices_secret_key = PrivateKey.generate()
print(bobs_secret_key)
print(type(bobs_secret_key))

# Bob's public key can be given to anyone wishing to send Bob an encrypted message
bobs_public_key = bobs_secret_key.public_key
# Alice does the same and then Alice and Bob exchange public keys
alices_public_key = alices_secret_key.public_key
print(bobs_public_key)
print(type(bobs_public_key))

# Bob wishes to send Alice an encrypted message so Bob must make a Box with his private key and Alice's public key
bobs_box = Box(bobs_secret_key, alices_public_key)
print(bobs_box)
print(type(bobs_box))

# This is our message to send, it must be a bytestring as Box will treat it
#   as just a binary blob of data.
secret_message = b"I am Satoshi"
encrypted = bobs_box.encrypt(secret_message)
print(encrypted)
print(type(encrypted))

# Alice creates a second box with her private key to decrypt the message
alices_box = Box(alices_secret_key, bobs_public_key)

# Decrypt our message, an exception will be raised if the encryption was
#   tampered with or there was otherwise an error.
plaintext = alices_box.decrypt(encrypted)
print(plaintext)
print(type(plaintext))
print(plaintext.decode('utf-8'))      
import nacl.encoding
import nacl.signing

# Generate a new random private key for Bob (we call this a signing key)
bobs_private_key = nacl.signing.SigningKey.generate()
print(bobs_private_key)
print(type(bobs_private_key))

# Sign a message with it
signed = bobs_private_key.sign(b"Attack at Dawn")
print(signed)
print(type(signed))

# Obtain the verify key for a given signing key
bobs_public_key = bobs_private_key.verify_key
print(bobs_public_key)
print(type(bobs_public_key))

print(bobs_public_key.verify(signed))

# Serialize the verify key to send it to a third party
bobs_public_key_hex = bobs_public_key.encode(encoder=nacl.encoding.HexEncoder)
print(bobs_public_key_hex)
print(type(bobs_public_key_hex))
bobs_private_key = bobs_private_key.encode(encoder=nacl.encoding.HexEncoder)
print(bobs_private_key)
print(type(bobs_private_key))