Security and Cryptography in Python - Hash Functions(2)

Security and Cryptography in Python - Hash Functions(2)

Digital Signatures works - uses hash functions

https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Signing_messages

Generate the public key and secret key:

image-20210227140337738

Code in Python;

import hashlib

# These are Alice's RSA keys
# Public key (e, n): 3 279379
# Secret key(d) 46387
n = 279379
e = 3
d = 46387

# This is the message that Alice wants to sign and send to Bob
message = "Bob you are awesome".encode()

# Step 1: hash the message
sha256 = hashlib.sha256()
sha256.update(message)
h = sha256.digest()
h = int.from_bytes(h, "big") % n
print("Hash value", h)
# Step 2:decrypt the hash value(use secret exponent)
sign = h**d % n
# Step 3: send message with signature to Bob
print(message, sign)

# Bob verifying the signature
# Step 1: calculate the hash value of the message
sha256 = hashlib.sha256()
sha256.update(message)
h = sha256.digest()
h = int.from_bytes(h, "big") % n
print("Hash value", h)
# Step 2: Verify the signature
verification = sign**e % n
print("Verification value", verification)

Running Result:

image-20210227140306885

Eve trying to modify a signed message

import hashlib

def modify(m):
    l = list(m)
    l[0] = l[0] ^ 1
    return bytes(l)

# These are Alice's RSA keys
# Public key (e, n): 3 279379
# Secret key(d) 46387
n = 279379
e = 3
d = 46387

# This is the message that Alice wants to sign and send to Bob
message = "Bob you are awesome".encode()

# Step 1: hash the message
sha256 = hashlib.sha256()
sha256.update(message)
h = sha256.digest()
h = int.from_bytes(h, "big") % n
print("Hash value", h)
# Step 2:decrypt the hash value(use secret exponent)
sign = h**d % n
# Step 3: send message with signature to Bob
print(message, sign)

# This is Eve being evil and modifies the message
message = modify(message)
print(message)

# Bob verifying the signature
# Step 1: calculate the hash value of the message
sha256 = hashlib.sha256()
sha256.update(message)
h = sha256.digest()
h = int.from_bytes(h, "big") % n
print("Hash value", h)
# Step 2: Verify the signature
verification = sign**e % n
print("Verification value", verification)

Running result (The hash values is different now):

image-20210227155602832

posted @ 2021-02-27 14:04  晨风_Eric  阅读(52)  评论(0编辑  收藏  举报