07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

274 Chapter 9 ■ Mastering Cryptography Using Python

def generateSharedSecret(self, privateKey, receiverPublicKey):

"""

Generates the shared secret after checking if receiverPublicKey

is valid.

"""

prime)

if (self.testReceiverPublicKey(receiverPublicKey) == True):

sharedSecret = pow (receiverPublicKey, privateKey, self.

return sharedSecret

else:

raise Exception ("Invalid public key.")

def generateSharedKey (self, receiverPublicKey):

"""

Gets shared secret, then hash it to obtain the shared key.

"""

self.sharedSecret = self.generateSharedSecret(self.privateKey,

receiverPublicKey)

try:

_sharedSecretBytes = self.sharedSecret.to_bytes(self.

sharedSecret.bit_length() // 8 + 1, byteorder="big")

except AttributeError:

_sharedSecretBytes = str(self.sharedSecret)

shared = hashlib.sha256()

shared.update(bytes(_sharedSecretBytes))

self.key = shared.digest()

def getSharedKey (self):

"""

Return shared secret Key

"""

return self.key

def displayParameters (self):

"""

Display parameters used on the DH agreement.

"""

print(">>>>>>> Parameters:")

print("Prime[{0}]: {1}\n".format(self.prime.bit_length(), self.

prime))

print("Generator:", self.generator, "\n")

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!