Implementing Cryptography Using Python 1st Edition Shannon Bray pdf download
Implementing Cryptography Using Python 1st Edition Shannon Bray pdf 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.
Discovering Diverse Content Through
Random Scribd Documents
Enter TOM, as Don Giovanni, with KATE as Domino.
Tom. (Advancing with Kate). Could I find one of your sex that would
be faithful, I would never rove again.
Kate. Are you sincere?—
Tom. By heaven!—I am!
Kate. Then behold the reward of your sincerity, the constancy of
your faithful Kate. (Unmasks).
Tom. Kate! oh, my dear Kate!
Enter LOGIC, as Doctor Pangloss, with JANE in Domino.
Log. (Advancing with Jane). I am an L.L.D. and A.S.S.
Jane. (Unmasks). You are indeed an A-S-S, not to have found me
out before.
Log. What! my Jenny!——
Jerry. Don’t be astonished, Bob—I’ll explain all:—Tom and I are
going to make two matches; you must make the third—form a
bunch of matches—exchange one imprisonment for another, her
arms, you dog!—’aint you up?—
Log. I’m fly—Oxford has no fellowship like this! (Embracing Jane).
Tom. (Coming down with Kate). You are right, Bob, it has not.—Well,
we have been amused by Life in London, now let us endeavour to
profit by it;—let our experience teach us to avoid its quicksands, and
make the most of its sunshine;—and in that anticipation let us hope
our kind friends will pardon Tom, Jerry, and Logic all their sprees and
rambles.
The Dustman.
To Start from the Winning Post on the Stage; Run three times Round
the Course.
Separate Matches, and afterwards for the Grand Sweepstakes.
PONY RACES.
Passing Into and Round the Pit.
Ponies. Colours.
1.—The Corinthian Pink.
2.—Bob Logic’s Miss Sly Stripe.
3.—Jerry’s Never to be beat Blue.
4.—Dusty Bob Black.
5.—Touch and-Go Blue and Pink.
6.—The Out-and-Outer Scarlet.
Stewards of the Race Logic, Tom, and Jerry.
Clerk of the Course Dusty Bob.
SADLER’S WELLS.
PIERCE EGAN,
The Author
of
(Before “all the Gold is taken off the Gingerbread,” being contented
with a Small Slice of it,) his
BENEFIT
is fixed for
Wednesday
The 25th September, 1822.
When a Variety Entertainment, will be performed, in which
THE AUTHOR
Will make his First and only Appearance on this Stage, in a
PRINCIPAL CHARACTER.
LIFE IN A SPREE.
A Spree’s the thing, with potent port made merry,
“Go it Bob Logic,” “Keep it up,” cries Jerry.
The Upper Story all abroad—Mr. Lushington at Work; and when the
Wine is in, the Wit is out—Ripe for any thing—How to make a Stop—
Watch go—And getting the best of the Timekeepers—Must make a
noise in the World:—
No way but this left to obtain renown,
Kick up a Row, and knock the Charlie’s down!
“When death showed his Nob, out of Time they were beat,
And neither would come to the scratch;
They hung down their heads and gave up the last heat,
Not prepared with the Spectre to match.
“All wept at the Funeral! the Fancy and all—
Some new, but a great many mended:
And Egan, while Cruikshank and Bob held the pall,
As Chief Mourner in person attended!!!
Text of Image
BILLY WATERS.
Mr. W. T. Moncrieff, the dramatist, is responsible for the following
biographical notice of this old London Street Character:—“Of this
meritorious and lamented individual, we had with great trouble
collected from various sources, an ample and interesting Biography.
But unfortunately for posterity, in the same classic regions where he
lost his life, we also lost his life; and, to tell the truth under the
influence of the same seductive fluid too—Daffy!—we can therefore
only present our reader with a few brief notices from memory.”
Billy Waters, was born in the powerful African kingdom of
Tongocongotaboo, where he was a native Prince, and bore the name
of Pokikokiquanko; from this place he was at an early age, to the
universal regret of his loving subjects, kidnapped, by ‘an auld
Quaker,’ who bought him from his treacherous attendants, for two
axes, a frying-pan and a bag of nails. This black piece of business
made him a slave, in the French settlement, at Demarara, from
whence however he speedly took French leave, and entered, we
believe, the British navy as a cook par excellence on board the
Ganymede sloop of war, under the command of Sir John Purvis,
where, during a fierce engagement, he lost a leg, some say gallantly
fighting the enemies of old England, though others insinuate it was
through falling down the cockpit ladder, in his great hurry to hide
himself. His own version was that he fell from the top-sail yard to the
quarter deck during a storm, we cannot pretend to decide which was
the fact, it however occasioned his being sent to England, as unfit
for service. Arriving in London, he betook himself to that wild mode
of life, which best suited his origin; the trammels of civilized society,
had no charm for him; he scorned the mechanical rules of man, and
picked up his living wherever he could find it. Born a Prince, and
bearing a native princeliness in his appearance it is not to be
wondered at that his associates should speedly elect him to the regal
dignity of their tribe.
In the year 1812 Billy was solemnly inauguared ex cathedra into the
sovereignty of mendicityship—King of the Beggars—at the cellar of
St. Patrick in St Giles’, a rank he supported with great satisfaction
and majesty, till the luckless period when a rival Billy (Bodkin), by
being placed at the head of the mendicity society, virtually became
King of the Beggars in his own right. This—as he conceived it, cruel
usurpation by Bodkin, pricked Billy just a leetle too hard. From that
moment he drooped as a blighted lily, and like another black hero he
exclaimed—‘Othello’s occupation’s gone.’ The fickle British public
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
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