Implementing Cryptography Using Python 1st Edition Shannon Bray download
Implementing Cryptography Using Python 1st Edition Shannon Bray download
https://ebookname.com/product/implementing-cryptography-using-
python-1st-edition-shannon-bray/
https://ebookname.com/product/implementing-soa-using-java-ee-1st-
edition-b-v-kumar/
https://ebookname.com/product/beginning-python-using-
python-2-6-and-python-3-1-wrox-programmer-to-programmer-james-
payne/
https://ebookname.com/product/python-high-performance-
programming-boost-the-performance-of-your-python-programs-using-
advanced-techniques-1st-edition-gabriele-lanaro/
https://ebookname.com/product/adventures-in-the-bone-trade-the-
race-to-discover-human-ancestors-in-ethiopia-s-afar-
depression-1st-edition-jon-kalb-auth/
Poverty and Charity in the Jewish Community of Medieval
Egypt Mark R. Cohen
https://ebookname.com/product/poverty-and-charity-in-the-jewish-
community-of-medieval-egypt-mark-r-cohen/
https://ebookname.com/product/insurance-and-the-law-of-
obligations-1st-ed-edition-merkin/
https://ebookname.com/product/overlay-crochet-jewelry-melody-
macduffee/
https://ebookname.com/product/m36-m36b-1-tank-destroyer-1st-
edition-david-doyle/
https://ebookname.com/product/international-law-and-post-
conflict-reconstruction-policy-1st-edition-matthew-saul-editor/
Oxford English for Information Technology Teacher s
Book Eric H. Glendinning
https://ebookname.com/product/oxford-english-for-information-
technology-teacher-s-book-eric-h-glendinning/
Implementing
Cryptography Using
Python®
Shannon W. Bray
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
ISBN: 978-1-119-61220-9
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.
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
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
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
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.
1
Introduction to Cryptography
and Python
1
Implementing Cryptography Using Python®, First Edition. Shannon W. Bray.
© 2020 John Wiley & Sons, Inc. Published 2020 by John Wiley & Sons, Inc.
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.
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).
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.
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
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.
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
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).
To use IPython, type IPython3 -h at the system command line. You can start
the shell by typing this:
~$ IPython3
In [1]:
Please note that you will need to pay attention to the version of Python; this
example is using Python 3.5.3, but you may see something like Python 2.x if you
did not specify IPython3. When Python 3 first came out, many libraries didn’t
exist, so many people stayed with 2.x. Python 3 has caught up and is now a
great language. There are, however, a few differences between Python 2.x and
Python 3, so if you find that some of your scripts fail, try running them using
an alternate version.
Another Random Document on
Scribd Without Any Related Topics
H.
Haggard, 57–59.
Halcyon, 275.
days, 275.
Hare, 11, Intro.
Hawks, 49.
how to seel, 70.
keep of, 79.
trappings of, 58–64.
value of, 77, 78.
unmann’d, 62.
Hawking, age of, 50.
sundries, 80–82.
terms, 51.
Hedgehog, 13, Intro.
Hernshaw, 75, 223.
Heron, 223.
-hawking, 224–228.
in bills of fare, 228.
Hood, 61.
Hounds, 8, 9, Intro.
Hunting, 4, Intro.
I.
Jackdaw, 119.
Jay, 121.
Jesses, 58, 59.
Imping, 67, 68.
Jove’s bird, 28, 29.
K.
Kestrel, 73.
Kingfisher, 275.
Kite, 43–47.
habits of, 46.
nest of, 47.
ill-omened, 45.
L.
Lang-nebbit things, 228.
Lapwing, 221.
decoying from nest, 221.
Lark, 130.
at heaven’s gate, 132.
herald of morn, 131.
soaring and singing, 135.
song of the, 130–134.
method of taking, 130.
the ploughman’s clock, 133.
Lime, 160.
Loon, 258, 259.
Lure, description of the, 55.
use of the, 56.
M.
Magpie, 120.
Mallard, 238.
Marten, 33.
Martin, 277.
Martlet, 277, 278.
Mole, 13, Intro.
Moth, 17, Intro.
Mew, 64.
origin of the word, 65.
Mews, the Royal, 65, 66.
Musket, 74.
N.
Night-crow, 102.
Nightingale, 124.
lamenting, 125.
recording, 129.
singing against a thorn, 126, 127.
singing by day, 128.
song of, 124.
O.
Owl, 83–98.
its associations, 83.
its character maligned, 93.
320 Owl, its comrades, 97.
its fame in song, 96.
its five wits, 95.
its habits misunderstood, 86.
its utility to the farmer, 87.
its use in medicine, 84.
its note, 90.
its retiring habits, 94.
robbing nests, 91.
of ill-omen, 85.
Osprey, 41.
its power over fish, 43.
Ostrich, 286.
Ouzel, 139.
P.
Parrot, 272.
-teacher, 273.
Partridge, 216.
in kite’s nest, 216.
-hawking, 217.
netting-, 218.
Peacock, 175.
introduction of, 176.
value of, 175.
variety of, 176.
Peewit, 222.
Pelican, 286.
fable of the, 287.
explanation of fable, 288–294.
Pelicans in England, 295.
Pheasant, 210.
introduction of, 211.
-hawking, 217.
Pigeon, 180.
Barbary-, 189.
Carrier-, 183.
domesticated, 181.
-fanciers, 182.
feeding young, 186.
-liver’d, 185.
-post, 184.
price of, 196.
Pitch, 51.
Plantage, 192.
Point, 51.
Prune, 31.
Q.
Quail, 218.
-fighting, 219.
note of the, 220.
Quaint recipes, 71.
Quarry, 57.
R.
Rabbit, 12, Intro.
-netting, 12, Intro.
Raven, 100.
of ill-omen, 101.
deserting its young, 106.
feathers of, 107.
food of, 105.
presence on battle-fields, 104.
supposed prophetic power, 103.
variety of, 109.
Recipes, quaint, 71.
Redbreast, 139.
-teacher, 142.
Robin, 139.
Rock-dove, 190.
Rook, 121.
Ruddock, 140.
covering with leaves, 141.
S.
Sea-fowl, 235.
Sea-gulls, 266.
Sea-mells, 270.
Seel, 69.
Seeling, 69.
Slow-worm, 16, Intro.
Snake, 13, 15, Intro.
Snipe, 233.
-netting, 234.
Souse, 38, 39.
Sparrow, 144.
fall of a, 146.
hedge-, 147.
321 Sparrow, Philip, 145.
value of a, 146.
Sparrowhawk, 73.
Springes, 229.
how to make, 230.
Stag, wounded, 10, Intro.
Stale, 244.
how to make a, 245.
Stalking, 238.
Stalking-horse, 238.
Starlings, 274.
talking, 274.
Stoop, 63.
Swallow, 277.
Swallow’s herb, 279.
stone, 283.
Swan, 201.
habits of the, 204.
nest of the, 204.
song of the, 202.
Swan’s down, 206.
Swans of Juno, 206.
warrant for, 207.
Squirrel, 13, Intro.
T.
Tassel-gentle, 54.
Tercel, 53.
and Falcon, 52.
Throstle, 137.
song of the, 138.
Tire, 38.
Tower, 39, 51.
Towering, 39, 51.
Toad, 13, 15, Intro.
Tradition, a curious, 88.
Trout, 3, Intro.
Turkey, 177.
introduction of, 177.
Turkey-fowl, 179.
Turtle-dove, 191.
V.
Vulture, 40.
repulsive habits of, 41.
W.
Wagtail, 156.
Wasp, 17, Intro.
Watching, 45.
Weasel, 13, 32.
Wild-cat, 13, Intro.
Wild-duck, 237.
Wild-fowl, 235, 257.
Wild-goose, 246.
Wild-goose chase, 199.
Winter-ground, 141.
Wren, 142.
courage of, 143.
pugnacity of, 143.
song of, 143.
Woodcock, 228, 271.
springe for a, 229.
Woodcock’s head, the, 232.
Punctuation has been standardised, and simple typographical errors have been repaired.
Variations in hyphenation and obsolete or variant spelling have been preserved.
The marker for Footnote 162 is missing in the original text, and has been left unmarked.
In the original book's List of Illustrations and Appendix, repeated text is indicated by
dittos; in this e-book, the repeated text is copied in full.
The cover image included with the EPUB and MOBI versions was made by the transcriber
and has been placed in the public domain.
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com