场景:
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))
======================================================