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.

268 Chapter 9 ■ Mastering Cryptography Using Python

# decrypt using Diffie-Hellman - ECC

def decrypt_dh(ciphertext, dhSecret):

# decrypt using the shared secret from Client (Private) and Server

(Public)

ciphertext = ciphertext.decode('utf-8')

plaintext = decrypt_AES_GCM(ciphertext,dhSecret)

#reverse = encrypt_AES_GCM(ciphertext, dhSecret)

return plaintext

# generate ECC certs

def gen_ecc_certs():

key = ECC.generate(curve='P-256')

f = open('myprivatekey.pem','wt')

f.write(key.export_key(format='PEM'))

f.close()

f = open('myprivatekey.pem','rt')

key = ECC.import_key(f.read())

print (key)

# encrypt using AES-GCM

def encrypt_AES_GCM(msg, secretKey):

aesCipher = AES.new(secretKey, AES.MODE_GCM)

ct, authTag = aesCipher.encrypt_and_digest(msg)

ct = hexlify(ct)

ct = ct.decode('utf-8')

authTag = hexlify(authTag)

authTag = authTag.decode('utf-8')

noncea = hexlify(aesCipher.nonce)

nonce = noncea.decode('utf-8')

ciphertext = json.dumps({'nonce':nonce, 'ciphertext':ct,

'tag':authTag})

return ciphertext

# decrypt using AES-GCM

def decrypt_AES_GCM(encryptedMsg, secretKey):

b64 = json.loads(encryptedMsg)

nonce = str(b64['nonce'])

nonce = nonce.encode()

nonce = unhexlify(nonce)

ct = str(b64['ciphertext'])

ct = ct.encode()

ct = unhexlify(ct)

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

Saved successfully!

Ooh no, something went wrong!