07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

270 Chapter 9 ■ Mastering Cryptography Using Python

if data == b'removeDH':

useDH = False

return 20

return 1

Creating the Diffie-Hellman Class File

There are many cryptographic libraries that will handle the Diffie-Hellman

exchange for you, and the DH primes listed in this section are a bit brutal to

type; the code listed in this section is presented more to help you understand

how the protocol works. This code, like all of the code in this book, is available

on the book’s website. This section is mostly for students who need to understand

how to generate the Diffie-Hellman exchange in other languages that

may not have libraries for it or for those of you in academia:

import hashlib

from binascii import hexlify

try:

#Preferably using urandom (more secure)

import os

random_function = os.urandom

random_provider = "OS random"

except (AttributeError, ImportError):

import ssl

random_function = ssl.RAND_bytes

random_provider = "Python SSL"

class DiffieHellman():

"""

Using standard primes from RFC 3526 MODP Groups 17 and 18.

Both are sufficient to generate AES 256 keys with a 540+ bit

exponent.

https://datatracker.ietf.org/doc/rfc3526/

"""

def __init__ (self, generator = 2, group = 17, keyLength=2048):

"""

Generate the public and private keys

"""

#Length in bits

min_keyLength = 1024

default_keyLength = 2024

default_generator = 2

valid_generators = [2, 3, 7] #Must be primes

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

Saved successfully!

Ooh no, something went wrong!