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.

28 Chapter 1 ■ Introduction to Cryptography and Python

>>> url = 'https://raw.githubusercontent.com/noidentity29/

AppliedCryptoPython/master/dictionary.txt'

>>> r = requests.get(url)

>>> with open('/Users/ShannonBray/Downloads/dictionary.txt', 'wb') as f:

>>> f.write(r.content)

>>>

>>> # Retrieve HTTP meta-data

>>> print(r.status_code)

>>> print(r.headers['content-type'])

>>> print(r.encoding)

In this script, the open method is used once again to write binary data to

a local file. If you execute the script and go to your Downloads directory, you

should see your newly downloaded text file named secrets.txt.

Utilizing the requests module, you can also easily retrieve relevant metadata

about your request, including the status code, headers, and much more. In the

preceding script, you can see how we access some of this metadata.

You can also elect to use the curl bash command, such as in the following

example:

curl -O https://raw.githubusercontent.com/noidentity29/AppliedCryptoPython/

master/secret.txt

curl -O https://raw.githubusercontent.com/noidentity29/AppliedCryptoPython/

master/dictionary.txt

Introducing Python Modules

Python modules are special packages that extend the language. You saw your

first module when you used the import math call shown previously. You can

examine the modules that are loaded by typing dir(). As shown with the math

module, when a module is preinstalled, we can use the import command to

upload it. To examine the modules that are preinstalled on your system, type

the following:

>>> help()

help> modules

help> modules hashlib

q

The hashlib is a built-in module that is preinstalled that will allow you to

run hash functions. We will discuss hashing in detail throughout this book, but

for now, we will explore the use of hashlib as a module. Type import hashlib,

then in the terminal type hashlib. (enter the dot after hashlib), and press the

Tab key. You should see a list of methods, as shown in Figure 1.4. You can explore

these methods by typing the module and method followed by a question mark,

such as hashlib.sha256?.

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

Saved successfully!

Ooh no, something went wrong!