Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Implementing Cryptography Using

Python Shannon Bray


Visit to download the full and correct content document:
https://ebookmass.com/product/implementing-cryptography-using-python-shannon-br
ay/
Implementing
Cryptography Using
Python®
Shannon W. Bray
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2020 by John Wiley & Sons, Inc., Indianapolis, Indiana


Published simultaneously in Canada

ISBN: 978-1-119-61220-9

ISBN: 978-1-119-61222-3 (ebk)

ISBN: 978-1-119-61545-3 (ebk)

Manufactured in the United States of America

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted
under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission
of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clear-
ance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the
Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111
River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/
go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-
ranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all
warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be
created or extended by sales or promotional materials. The advice and strategies contained herein may not
be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in
rendering legal, accounting, or other professional services. If professional assistance is required, the services
of a competent professional person should be sought. Neither the publisher nor the author shall be liable for
damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation
and/or a potential source of further information does not mean that the author or the publisher endorses
the information the organization or website may provide or recommendations it may make. Further, readers
should be aware that Internet websites listed in this work may have changed or disappeared between when
this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included
with standard print versions of this book may not be included in e-books or in print-on-demand. If this book
refers to media such as a CD or DVD that is not included in the version you purchased, you may down-
load this material at http://booksupport.wiley.com. For more information about Wiley products, visit
www.wiley.com.

Library of Congress Control Number: 2020940306

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc.
and/or its affiliates, in the United States and other countries, and may not be used without written permis-
sion. Python is a registered trademark of Python Software Foundation. All other trademarks are the property
of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned
in this book.
To Stephanie, Eden, Hayden, and Kenna,
with all my love, for making each and every day special.
About the Author

Shannon W. Bray started his career in information technology in 1997 after


being honorably discharged from the United States Navy. He started his IT
career working on programmable logic controllers out in the Gulf of Mexico
and then started writing business applications using various technologies until
2000 when .NET was first released; since then, the languages of choice have
been C++, C#, Windows PowerShell, and Python. From there, Shannon worked
on writing software until he started working with Microsoft SharePoint. The
Microsoft stack of technologies forced Shannon out of just writing code into
building large secure solutions. Shannon’s career has taken him to engagements
all over the world where he has worked with a number of U.S. government
agencies. Shannon became interested in cryptography while pursuing a master’s
degree in cybersecurity, and he has continued to research cryptography and
cybersecurity as he pursues a PhD in computer science.
Shannon has earned the following certifications: Microsoft Certified Master,
Microsoft Certified Solutions Master, Certified Information Security Manager
(CISM), Security+ (Plus), the CompTIA Advanced Security Practitioner (CASP+),
and a number of other industry certifications. In addition to writing, Shannon
speaks nationally at technology conventions and works as a mentor teaching
technology to youth programs.
Shannon lives in the Raleigh, North Carolina, area with his wife, Stephanie,
two daughters, Eden and Kenna, and son, Hayden. During the dive season,
Shannon enjoys diving off the coast of North Carolina. During the rest of the
year, Shannon works on IT projects around the house that utilize single-board
computers and, most often, propellers. He is currently building a home security
system that uses Python, cryptography, and drones. As of the release of this

v
vi About the Author

book, Shannon is currently running for the U.S. Senate for the state of North
Carolina to help bring cybersecurity issues to the mainstream and to help people
understand the importance of end-to-end encryption.
Shannon can be contacted through LinkedIn at www.linkedin.com/in/
shannonbray.
Acknowledgments

While this is my third book, every book comes with its own set of challenges.
Completing a book is not always a fun project but does become a labor of love.
As soon as you start, life has a way of throwing changes at you, and it seems
that you never have the time that you thought you would have. Shortly after
starting this book, I started a PhD program with the Missouri University of
Science and Technology and transitioned through a number of government
contracts, ran for political office, and then became a work-from-home teacher
as the world battled a global pandemic. I knew that the editing team would be
earning their pay with whatever I put together. That team has been wonderful
with their feedback and responsiveness. Specifically, I’d like to thank the follow-
ing people on the Wiley team: Barath Kumar Rajasekaran, production editor;
Jim Minatel, acquisitions editor; Pete Gaughan, content enablement manager;
Brent Cook and James Langbridge, technical editors, and, most importantly,
Kim Wimpsett, the project editor. Kim did her best to keep me on schedule, but
I found new ways to miss a few deadlines.

vii
Contents at a Glance

Introductionxvii
Chapter 1 Introduction to Cryptography and Python 1
Chapter 2 Cryptographic Protocols and Perfect Secrecy 31
Chapter 3 Classical Cryptography 65
Chapter 4 Cryptographic Math and Frequency Analysis 95
Chapter 5 Stream Ciphers and Block Ciphers 139
Chapter 6 Using Cryptography with Images 171
Chapter 7 Message Integrity 199
Chapter 8 Cryptographic Applications and PKI 223
Chapter 9 Mastering Cryptography Using Python 247
Index277

ix
Contents

Introductionxvii
Chapter 1 Introduction to Cryptography and Python 1
Exploring Algorithms 2
Why Use Python? 2
Downloading and Installing Python 3
Installing on Ubuntu 4
Installing on macOS 4
Installing on Windows 4
Installing on a Chromebook 4
Installing Additional Packages 5
Installing Pip, NumPy, and Matplotlib 6
Installing the Cryptography Package 7
Installing Additional Packages 8
Testing Your Install 9
Diving into Python Basics 9
Using Variables 10
Using Strings 11
Introducing Operators 11
Understanding Arithmetic Operators 11
Understanding Comparison Operators 13
Understanding Logical Operators 13
Understanding Assignment Operators 14
Understanding Bitwise Operators 15
Understanding Membership Operators 15
Understanding Identity Operators 16

xi
xii Contents

Using Conditionals 16
Using Loops 17
for17
while18
continue18
break18
else18
Using Files 19
Understanding Python Semantics 20
Sequence Types 20
Introducing Custom Functions 26
Downloading Files Using Python 27
Introducing Python Modules 28
Creating a Reverse Cipher 29
Summary30
Chapter 2 Cryptographic Protocols and Perfect Secrecy 31
The Study of Cryptology 32
Understanding Cryptography 32
Cryptography’s Famous Family: Alice and Bob 33
Diffie-Hellman34
Data Origin Authentication 34
Entity Authentication 35
Symmetric Algorithms 36
Asymmetric Algorithms 36
The Needham-Schroeder Protocols 36
The Otway-Rees Protocol 38
Kerberos39
Multiple-Domain Kerberos 40
X.50941
Formal Validation of Cryptographic Protocols 46
Configuring Your First Cryptographic Library 47
Understanding Cryptanalysis 47
Brute-Force Attacks 47
Side-Channel Attacks 48
Social Engineering 48
Analytical Attacks 48
Frequency Analysis 48
Attack Models 49
Shannon’s Theorem 50
One-Time Pad 51
XOR, AND, and OR 51
One-Time Pad Function 56
One-Way Hashes 58
Contents xiii

Cryptographic One-Way Hashes 59


Message Authentication Codes 60
Perfect Forward Secrecy 60
Published and Proprietary Encryption Algorithms 61
Summary62
References62
Chapter 3 Classical Cryptography 65
Password Best Practices 66
Password Storage 66
Hashing Passwords 67
Salting Passwords 67
Stretching Passwords 68
Password Tools 68
Obfuscating Data 69
ASCII Encoding 70
Base64 Encoding Text 70
Binary Data 72
Decoding72
Historical Ciphers 72
Scytale of Sparta 73
Substitution Ciphers 73
Caesar Cipher 74
ROT-1376
Atbash Cipher 77
Vigenère Cipher 77
Playfair79
Hill 2x2 83
Column Transposition 87
Affine Cipher 90
Summary93
Chapter 4 Cryptographic Math and Frequency Analysis 95
Modular Arithmetic and the Greatest Common Devisor 96
Prime Numbers 97
Prime Number Theorem 98
School Primality Test 98
Fermat’s Little Theorem 100
Miller-Rabin Primality Test 100
Generate Large Prime Numbers 104
Basic Group Theory 106
Orders of Elements 107
Modular Inverses 109
Fermat’s Little Theorem to Find the Inverse 110
Extending the GCD 111
Euler’s Theorem 111
xiv Contents

Pseudorandomness115
Breaking C’s rand() Function 116
Solving Systems of Linear Equations 117
Frequency Analysis 120
Cryptanalysis with Python 123
Using an Online Word List 125
Determining the Frequency 126
Breaking the Vigenère Cipher 129
Summary138
Chapter 5 Stream Ciphers and Block Ciphers 139
Convert between Hexdigest and Plaintext 140
Use Stream Ciphers 141
ARC4147
Vernam Cipher 148
Salsa20 Cipher 149
ChaCha Cipher 151
Use Block Ciphers 156
Block Modes of Operations 158
ECB Mode 158
CBC Mode 159
CFB Mode 160
OFB Mode 162
CTR Mode 163
Tricks with Stream Modes 164
DIY Block Cipher Using Feistel Networks 165
Advanced Encryption Standard (AES) 167
Using AES with Python 167
File Encryption Using AES 169
File Decryption Using AES 169
Summary169
Chapter 6 Using Cryptography with Images 171
Simple Image Cryptography 171
Images and Cryptography Libraries 174
Understanding the Cryptography Library 174
Understanding the Cryptosteganography Library 175
Image Cryptography 175
File Cryptography Using Fernet 176
Image Cryptography Using Fernet 179
AES and Block Modes of Operations 180
Exploring a Simple ECB Mode Example 181
Exploring a Simple CBC Mode Example 185
Applying the Examples 186
Steganography187
Storing a Message Inside an Image 188
Contents xv

Storing a Binary File Inside an Image 192


Working with large images 195
Summary197
Chapter 7 Message Integrity 199
Message Authentication Codes 200
Hash-based Message Authentication Code 201
Using HMAC to Sign Message 202
Message Digest with SHA 203
Binary Digests 204
NIST Compliance 205
CBC-MAC206
Birthday Attacks 207
Crafting Forgeries 209
The Length Extension Attack 209
Setting Up a Secure Channel 210
Communication Channels 211
Sending Secure Messages over IP Networks 212
Create a Server Socket 212
Create a Client Socket 213
Create a Threaded Server with TCP 214
Adding Symmetric Encryption 215
Concatenate Message and MAC 218
Summary221
References222
Chapter 8 Cryptographic Applications and PKI 223
The Public-Key Transformation 224
Exploring the Basics of RSA 226
Generating RSA Certificates 229
Constructing Simple Text Encryption and
Decryption with RSA Certificates 231
Constructing BLOB Encryption and
Decryption with RSA Certificates 232
The El-Gamal Cryptosystem 235
Elliptic Curve Cryptography 238
Generating ECC Keys 240
Key Lengths and Curves 241
Diffie-Hellman Key Exchange 242
Summary245
Chapter 9 Mastering Cryptography Using Python 247
Constructing a Plaintext Communications Application 248
Creating a Server 248
Creating the Client 250
Creating the Helper File 251
Execution252
xvi Contents

Installing and Testing Wireshark 253


Implementing PKI in the Application Using RSA Certificates 255
Modifying the Server 256
Modifying the Client 257
Modifying the Helper File 258
Execution259
Implementing Diffie-Hellman Key Exchange 261
Modifying the Server File 262
Modifying the Client File 264
Modifying the Helper File 266
Creating the Diffie-Hellman Class File 270
Execution275
Wrapping Up 276
Index277
Introduction

I initiated my journey into cryptography while studying for my undergrad. Most


of the cryptography concepts I learned were based on what one would need for
their CISSP or Security+ exams. Most of my understanding was at a high level,
and it was difficult to remember the more intricate aspects until cryptography
became a primary focus.
It wasn’t until I started my master’s in cybersecurity that I began applying
cryptographic features within a scripting environment. The concepts in this
book will help you advance your knowledge and experience as you dig deeper
into understanding the use of cryptography in Python.
Over the past few years, several governments have discussed legislation that
will ensure that any form of communication, whether it’s an email, text message, or
video chat, can always be read by the police or intelligence services if they have a
warrant. Governments are putting pressure on technology companies to give them
backdoor access or the keys to the kingdom so that they can keep the country safe.
The fight between lawmakers and encrypted messaging platforms has entered
new territory. Imagine a world where the government has seized the oppor-
tunity to scan every electronic message by government-approved scanning
software. The privacy and security of all users will suffer if law enforcement
agencies achieve their dream of breaking cryptosystems. Proponents of end-to-
end encryption, like Microsoft, Facebook, and Google, may lose their campaign
to maintain user security as a priority.
We have all heard of times when it would be beneficial for encrypted data
to magically become readable; this is often related to criminal cases. Should
criminals be allowed to plot their plans in secret? Where does the right to our
privacy start? In reality, there are technical and legal issues with allowing gov-
ernments to do this; this of course will be strongly opposed by technology and

xvii
xviii Introduction

privacy advocates. The world is at war on what can be encrypted, what should be
encrypted, and who should have the keys to unlock someone else’s encryption.
Whether you agree or disagree with what powers a nation-state should have
over encrypted communications in their country, you should understand what
encryption is, how to apply it when needed, and how to ensure that the data
you are receiving is authentic and confidential. Over the course of this book,
you will get a basic understanding of how to cryptographically secure your
messages, files, or Internet traffic using easy-to-understand Python recipes that
have been created or updated to support Python 3.

What This Book Covers


This book focuses on helping you pick the right Python environment for your
needs so that you can hit the ground running. You will get an understanding
of what algorithms are and explore the basics of Python.
Once you have an idea of where you are starting from, you will get an over-
view of what cryptography is, what perfect secrecy means, and the history of
cryptography and how its use changed our world.
To get a full understanding of some of the cryptographic concepts, a little
math is needed. You will get an understanding of how prime numbers, basic
group theory, and pseudorandom number generators help build cryptographic
solutions. This will build the foundation for understanding various stream and
block ciphers and highlight some of their encryption modes and weaknesses.
Every cryptographic discussion is better with pictures, so we will spend a
chapter focusing on how image cryptography and steganography work. We’ll also
highlight a few issues that you will need to be aware of while dealing with images.
Message integrity is just as important as message secrecy. Knowing who sent
the message to you directly relates to whether the message is credible. You will
learn how to generate message authentication codes to ensure integrity during
transit.
The strength of encryption will be shown at the end of the book when you
will learn about PKI schemes and explore how to implement elliptic curve cryp-
tography in an application. The application you build will exchange data in a
highly secure format over an unsecure channel, thus ensuring that you are able
to control your own end-to-end encryption scheme that no one will be able to
decrypt without the keys you create. I hope you find the journey as fun as I did.
Introduction xix

What You Need to Know


This book assumes that you are fairly new to cryptography. While there is a
brief introduction to how to set up and use Python, you will get the most out of
the book if you have experience in another programming or scripting language.

What You Need to Have


The concepts presented in this book can be executed on Microsoft Windows,
Linux, Chromebook, or iOS. Your choice of editor will most likely depend on
the underlying operating system, although most of the Python recipes presented
here will execute in online editors as well as most shells that are using a Python
interpreter that is 3.0 or greater.

How to Use This Book


The topics in this book get more advanced as you progress through it, so you
can work through the material from front to back and build your skills as you
go. You can also use this book as a reference that you can consult when you
need help with the following situations:
■■ You’re stuck while trying to figure out how to secure your data.
■■ You need to do something using cryptography that you’ve never
done before.
■■ You have some time on your hands, and you’re interested in learning
something new about Python and cryptography.
The index is comprehensive, and each chapter typically focuses on a single
broad topic. Don’t be discouraged if some of the material is over your head.
As you work through the coding samples and build out the final solution, the
concepts should become easier to understand.

What’s on the Website


Nearly everything discussed in this book has examples with it. You can (and
should) download the many useful examples included with this book. We have
verified that each file will run in environments that are Python version 3.0 and
higher.
The files are located at github.com/braycrypto/cryptography, as well as at
www.wiley.com/go/cryptographywithpython.
CHAPTER

1
Introduction to Cryptography
and Python

Cryptography is one of the most important tools we have at our disposal as


information security professionals. It provides us with the ability to protect
sensitive information from unauthorized disclosure through encryption. Cryp-
tography is the use of mathematical algorithms that can be used to transform
data either into an encrypted form (ciphertext) or into its decrypted form (plain-
text). The purpose of these algorithms can be quite complicated. The goal of this
book is to help simplify the use of cryptography using the available libraries
in Python, so you will begin your journey into cryptography by setting up a
Python environment. You’ll also get a review of using Python, and then you’ll
write your first cipher using Python. Specifically, you’ll do the following:
■■ Gain an understanding of algorithms
■■ Explore various Python installations
■■ Set up Python 3 on various machines
■■ Explore the basics of the Python language
■■ Write your first cipher using Python

1
2 Chapter 1 ■ Introduction to Cryptography and Python

Exploring Algorithms
The algorithms you will explore in this book can be quite sophisticated, but
most of the logic is encapsulated into little black boxes that allow you to inter-
face with the algorithms using functions. In the programming or mathematical
world, a function is merely a way to enter values and receive output. When using
algorithms in cryptography, we generally have two inputs for encryption and
two inputs for decryption:
■■ The encryption process will take the plaintext message (P) along with an
encryption key (K) and then run the plaintext through encryption algo-
rithms, which will return ciphertext (C).
■■ On the decryption side, the ciphertext (C) will be supplied along with the
encryption key (K), which will produce the plaintext (P) message.
As you study various encryption themes throughout this book, you will find
that they are described by three algorithms: GEN for key generation, ENC for
the encryption algorithm, and DEC for the decryption algorithm. You’ll revisit
this concept at the end of this chapter when you learn how to create a Python
function.

Why Use Python?


Using Python for cryptography is simpler than using languages such as C or
C++; while free libraries such as OpenSSL are available, their use can be quite
complex. Python removes these complexities with many built-in libraries that
aid in cryptography scripting. It is also a great choice because Python is free in
terms of license. Python can be described as an open-source, general-purpose
language that is object oriented, functional, and procedural, and it allows for
the interface with C/ObjC/Java/Fortran and even .NET. A number of versions
are available, from 2.5.x through 3.x. Currently, 3.x is becoming more popular
as new libraries are introduced. Python comes preinstalled with Linux and
macOS, and you can install it on Windows as well. You will learn how to install
Python in each of these environments later in this chapter.
Because Python is available for Windows, Linux/Unix, Mac, and Chrome-
books, among others, the lessons you learn here will be portable to several
environments. Python has proven to be quite powerful in information security
and can be used to quickly script solutions to help you become a better secu-
rity practitioner. If you are using Ubuntu Linux, every command you see in
Chapter 1 ■ Introduction to Cryptography and Python 3

this book will work. If you are on a Mac, you can use the Terminal app found
inside the Utilities folder. On a Windows machine, you have several options
as well: you can install a number of tools such as Cygwin, Visual Studio, or
PyCharm; use the Windows 10 Linux subsystem; or just install Ubuntu Linux
from the Microsoft Store. If you are new to Linux, I recommend practicing your
command-line skills a bit to help get you comfortable.
When you start the Python shell (by typing python or python3 at the command
line), you will see the version and the date associated with the version. For in-
stance, if you install and run Python in a Linux environment, you should see
something similar to the following:
Python 3.7.4+ (default, Sep 4 2019, 08:03:05)
[GCC 9.2.1 20190827] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The majority of Python interpreters use >>> as a prompt to accept user input;
one notable exception is IPython, which is discussed briefly in a moment. Once
you are in a Python shell, exit by pressing CTRL+D or typing exit(). Python
files use a .py extension, and we start their execution in Linux environments
by typing python3 filename.py; (keep in mind that you still need to chmod
+x the file).

N OT E In Unix-like operating systems, the chmod command sets the permissions


of files or directories.

As you will learn later in this chapter, a large number of modules are avail-
able for Python, many of which we will use along your journey of learning
cryptography. One of the more notable modules you will learn more about is
NumPy. NumPy offers numerical operations to Python, including fast multi-
dimensional array operations, random number generation, and linear algebra.
Another module that you will be introduced to is Matplotlib, which is an excel-
lent library for plotting. In Chapter 6, you will learn more about PyFITS, which
is a module that provides access to Flexible Image Transport System (FITS) files.
FITS is a portable file standard that is widely used throughout the astronomy
community to store images and tables. We will be combining it with our cryp-
tography techniques to encrypt and decrypt image files.

Downloading and Installing Python


You can download the Python interpreter from www.python.org/python, where
you’ll find versions for Ubuntu, macOS, and Windows. Be sure to download
version 3.7 or higher, since Python 2 is now unsupported.
4 Chapter 1 ■ Introduction to Cryptography and Python

Installing on Ubuntu
If you are running Ubuntu, install Python from the Ubuntu Software Center
using these steps:
1. Open the Ubuntu Software Center.
2. In the search box in the top-right corner of the window, type Python.
3. Select IDLE.
4. Click Install.

Installing on macOS
If you are using macOS, download the .dmg file for your version of macOS and
execute it. When the DMG package opens, do the following:
1. Double-click the Python package file (.mpkg).
2. Click Continue through the Welcome section and click Agree to accept
the license.
3. Select HD Macintosh and click Install.

Installing on Windows
If you are using Windows, download and run the Python installer; it should
have an .msi extension. Then follow these steps:
1. Click Install Now to begin the installation.
2. When the installation completes, click Close.
Notice the mention of upgrading. You can upgrade a package by clearing out
the Search PyPI and Installed Packages search box. This will show you all of
the installed packages. Any package that has an update will have an up arrow
next to it along with the newer version number (see Figure 1.1). You may have
to elevate your privileges.

Installing on a Chromebook
New Windows and Chrome OS computers give you the ability to install Linux.
The Chrome OS, which is becoming more popular, enables you to install a Linux
container that you can interact with but also keeps the rest of the environment
isolated so that you do not have to worry about messing up your system.
Chapter 1 ■ Introduction to Cryptography and Python 5

Figure 1.1: Upgrading packages

To get started with Python 3 on a Chromebook, click the time in the lower-
right corner. If you have the appropriate permissions on the Chromebook, you
should see a Settings button that looks like a flower with a dot in the middle
of it. Once you are in Settings, you can scroll down until you find Linux (Beta)
and then enable it by clicking Turn On. It may take several minutes, but once
it is complete, you will be able to run Linux tools, editors, and IDEs on your
Chromebook. To continue with the Chromebook installation, see the next sec-
tion for instructions on how to install NumPy and Matplotlib.

Installing Additional Packages


Many of the coding recipes that you will find in this book require additional
packages or modules to help reduce the amount of code you need to write to
ensure message security. Most Python interpreters use a command-line approach
of loading the packages. Integrated development environments (IDEs) may have
unique ways of loading packages for each interpreter available.
6 Chapter 1 ■ Introduction to Cryptography and Python

Installing Pip, NumPy, and Matplotlib


Ensure you are in a command shell environment with a prompt. In the follow-
ing example installation, you will get an update to the packages that come with
your Python version.
Pip, or Pip3 in this case, is the package management system for Python; it is
used to install and manage software packages written in Python. Pip is similar
to tools like Bundle, NPM, and Composer in other programming languages.
NumPy, which stands for Numerical Python, is a Python package that is the
core library for scientific computing. It contains a powerful n-dimensional array
object, and provides tools for integrating C, C++, and many other languages.
Matplotlib is an excellent solution for scientific plotting; it has the ability to be
automated and produce a wide variety of customizable high-quality plots.
Once the shell is open, type the following commands:
~$ sudo apt-get update
~$ sudo apt install python-pip
~$ pip3 install numpy
~$ pip3 install matplotlib

~$ $ python3 -c "import numpy as np; import matplotlib.pyplot as plt; x


= np.linspace(0, 2 * np.pi); y = np.sin(x); plt.plot(x, y); plt.show()"

N OT E Depending on your environment, you may need to install python3-pip to


get Pip3 to work. On installs such as Ubuntu 16.04 on Windows, you will not be able to
install version 3 when you install python-pip.

To start the Python 3 shell, type the following:


~$ python3

You should see something similar to the following depending on the version
that is installed:
Python 3.X.X (default, date)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

To test whether you have the additional packages installed correctly, open
your favorite Python editor. If you don’t have one, you can elect to use Nano in
a Linux environment or even Notepad in a Windows environment. Type the
following:
#!/usr/bin/env python

import numpy as np
Chapter 1 ■ Introduction to Cryptography and Python 7

import matplotlib.mlab as mlab


import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green',
alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

Save the file as matplot.py and execute the file. The preceding Python recipe
will generate a plot using NumPy and the Matplotlib library (see Figure 1.2).

Figure 1.2: Matplot.py test

Installing the Cryptography Package


Python has a Cryptography package that provides cryptographic recipes and
primitives to Python developers. It is designed to be your “cryptographic stan-
dard library.” As of this writing, it supports Python 2.7, Python 3.4+, and PyPy
5.4+. You can install the Cryptography package by using Pip3. The syntax is
as follows:
$ pip3 install cryptography
Another random document with
no related content on Scribd:
*** END OF THE PROJECT GUTENBERG EBOOK GAY-NECK ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree to
abide by all the terms of this agreement, you must cease using
and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite
these efforts, Project Gutenberg™ electronic works, and the
medium on which they may be stored, may contain “Defects,”
such as, but not limited to, incomplete, inaccurate or corrupt
data, transcription errors, a copyright or other intellectual
property infringement, a defective or damaged disk or other
medium, a computer virus, or computer codes that damage or
cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES -


Except for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU
AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE,
STRICT LIABILITY, BREACH OF WARRANTY OR BREACH
OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE
TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER
THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR
ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE
OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF
THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If


you discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person or
entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you do
or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status by
the Internal Revenue Service. The Foundation’s EIN or federal
tax identification number is 64-6221541. Contributions to the
Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or
determine the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.

You might also like