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 1 ■ Introduction to Cryptography and Python 29

Figure 1.4: Module methods

Now that you understand the importance of Python modules, let’s import

the hashlib library and then use the MD5 and SHA message digests. Type the

following in Python:

>>> import hashlib

>>> hashlib.md5('hello world'.encode()).hexdigest()

'5eb63bbbe01eeed093cb22bb8f5acdc3'

>>> hashlib.sha512('hello world'.encode()).hexdigest()

'309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f

989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f'

NOTE

are hashed.

Python 3 and higher require that Unicode objects be encoded before they

Creating a Reverse Cipher

For this next exercise, we build on what we have learned in this chapter by creating

a function named reverseCipher that accepts one parameter: plaintext.

We can then call our function and pass the plaintext into it and print out the

return ciphertext. Our method modifies the plaintext so that the ciphertext is

the complete reverse:

def reverseCipher(plaintext):

ciphertext = ''

i = len(plaintext) - 1

while i >= 0:

ciphertext = ciphertext + plaintext[i]

i = i - 1

return ciphertext

plaintext = 'If you want to keep a secret, you must also hide it from

yourself.'

ciphertext = reverseCipher (plaintext)

print(ciphertext)

This code should produce the following result:

.flesruoy morf ti edih osla tsum uoy ,terces a peek ot tnaw uoy fI

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

Saved successfully!

Ooh no, something went wrong!