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.

Chapter 9 ■ Mastering Cryptography Using Python 273

(https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_

number_generator)

"""

randomNumber = 0

_bytes = bits // 8 + 8

while (randomNumber.bit_length() < bits):

randomNumber = int.from_bytes(random_function(_bytes),

byteorder='big')

return randomNumber

def generatePrivateKey(self, bits):

"""

Generate the private key

"""

return self.generateRandomNumber(bits)

def generatePublicKey(self):

"""

Generate public key with generator ** privateKey % prime

"""

return pow(self.generator, self.privateKey, self.prime)

def testReceiverPublicKey (self, receiverPublicKey):

"""

Checks receiver Public Key to make sure it's valid.

Since a safe prime is used, verify that the Euler's Criterion

for the Legendre Symbol == 1

Not super trustworthy tho, it has its limitations.

(https://en.wikipedia.org/wiki/Legendre_symbol)

(https://www.youtube.com/watch?v=o23itWTcEYw)

"""

if (receiverPublicKey > 2 and receiverPublicKey < self.prime - 1):

if(pow(receiverPublicKey, (self.prime - 1)//2, self.prime) == 1):

#if it's a quadratic residue

return True

return False

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

Saved successfully!

Ooh no, something went wrong!