Free book sample

Practical Python Cryptography

Secure Your Applications with Modern Encryption Techniques

Imagine building applications where your users' sensitive data is genuinely protected—where passwords are securely hashed, communications are encrypted end-to-end, and you can verify the authenticity of digital transactions with confidence.

222 pages11 chaptersFeb 28, 2026Cryptography

Download sample:

About this book

This book shows you exactly how to achieve that using Python. You'll move beyond theoretical cryptography to practical, working code. Learn how to implement symmetric encryption for protecting data at rest, use asymmetric encryption for secure key exchange, and apply digital signatures to verify authenticity. Discover how to properly hash passwords, manage cryptographic keys without exposing them, and integrate encryption into real applications. Whether you're building web applications, APIs, or data processing systems, you'll find concrete examples and patterns you can use immediately. This guide covers the cryptographic libraries Python developers actually use, explains the reasoning behind security decisions, and helps you avoid the pitfalls that lead to vulnerabilities. By the end, you'll understand not just how to use cryptography, but why each technique matters for your application's security.

Table of contents

  1. IntroductionWhy Cryptography Matters in Modern Development, What You'll Learn in This Book, How to Use This Guide, Prerequisites and SetupRead below
  2. Chapter 1: Cryptography FundamentalsCore Cryptographic Concepts, Symmetric vs. Asymmetric Encryption, Understanding Threat Models
  3. Chapter 2: The Python Cryptography EcosystemAvailable Cryptographic Libraries, Choosing the Right Library for Your Needs, Installation and Setup, Security Best Practices from Day One
  4. Chapter 3: Symmetric Encryption in PracticeHow Symmetric Encryption Works, Implementing AES Encryption, Modes of Operation and When to Use Them, Real-World Symmetric Encryption Examples
  5. Chapter 4: Hashing and Data IntegrityHashing Principles and Properties, Secure Password Hashing, Verifying Data Integrity with Hashes, Common Hashing Pitfalls to Avoid
  6. Chapter 5: Asymmetric Encryption and Key ExchangeRSA Encryption Fundamentals, Generating and Managing RSA Keys, Implementing Public Key Encryption, Key Exchange Protocols and Diffie-Hellman
  7. Chapter 6: Digital Signatures and AuthenticationUnderstanding Digital Signatures, Signing and Verifying Data, Real-World Signature Applications
  8. Chapter 7: Cryptographic Key ManagementSecure Key Generation and Storage, Key Rotation and Lifecycle Management, Secure Key Distribution, Hardware Security Modules and Key Vaults
  9. Chapter 8: Authenticated Encryption and AEADAuthenticated Encryption with Associated Data, Implementing GCM Mode, Practical Authenticated Encryption Examples
  10. Chapter 9: Building Secure Communication SystemsTLS/SSL Overview and Python Integration, Working with Certificates and Certificate Chains, Building Secure APIs and Web Services, Implementing End-to-End Encryption
  11. Chapter 10: Advanced Cryptographic PatternsMulti-Party Computation and Secret Sharing, Zero-Knowledge Proofs Concepts, Introduction to Homomorphic Encryption
  12. Chapter 11: Testing and Auditing Cryptographic CodeTesting Cryptographic Implementations, Vulnerability Assessment and Penetration Testing, Security Code Review Practices
  13. ConclusionKey Takeaways, Your Next Steps in Cryptographic Security
  14. Appendix: Quick ReferenceAlgorithm Comparison Chart, Common Code Snippets

Introduction

Every day, millions of applications handle sensitive data: passwords, financial records, private messages, medical histories, and personal identifiers. Most of that data is protected by cryptography, whether the developers who built those applications fully understood it or not. The difference between applications that protect their users and applications that expose them often comes down to a handful of implementation decisions, made by developers who either understood the principles behind those decisions or were just guessing. This book is about making sure you are never guessing.

Python has become one of the most popular languages for building web applications, APIs, data pipelines, and backend services. It also has a mature, well-maintained ecosystem of cryptographic libraries that make it genuinely practical to implement strong security without a mathematics degree. Libraries like cryptography and PyCryptodome wrap complex algorithms in clean, developer-friendly interfaces. But a clean interface does not protect you from using the right tool in the wrong way. Understanding what you are doing, and why, is still essential.

This book bridges the gap between theory and practice. It does not ask you to become a cryptographer. It does ask you to understand enough about how cryptographic systems work so that you can use them correctly, recognize when something is wrong, and make informed decisions about which tools to reach for in a given situation. The goal is confident, correct implementation, not academic mastery. By the time you finish, you will have working code, a solid mental model of the cryptographic landscape, and the judgment to apply what you have learned to your own projects.

One principle runs through every chapter of this book: never implement cryptography from scratch. The algorithms that protect modern software have been designed, analyzed, and tested by specialists over decades. Reimplementing them introduces subtle vulnerabilities that are nearly impossible to detect through normal testing. The right approach is to use battle-tested libraries, understand their interfaces, and apply them correctly. That is exactly what this book teaches you to do.

Why Cryptography Matters in Modern Development

Data breaches have become a routine headline. In 2023 alone, billions of records were exposed across industries ranging from healthcare to retail to government services.[1] Many of those breaches were not the result of exotic, nation-state-level attacks. They were the result of predictable failures: passwords stored in plain text, unencrypted databases, API endpoints that did not verify the identity of callers, and encryption keys stored alongside the data they were supposed to protect. These are not exotic mistakes. They are the kinds of mistakes that happen when developers treat security as an afterthought.

Cryptography is the foundational technology that prevents these failures. It is what makes it possible to store a password so that even if your database is stolen, the attacker cannot log in as your users. It is what makes it possible to send data across an untrusted network without exposing it to anyone who might be listening. It is what makes it possible to verify that a document, a software update, or an API request actually came from who it claims to have come from. Without cryptography, none of the trust that modern software depends on would be possible.

For developers, this is not an abstract concern. Consider a straightforward scenario: you are building a web application that stores user health records. Those records are sensitive by definition, and in many jurisdictions they are protected by law. If you store them in a database without encryption, a single SQL injection vulnerability or a misconfigured cloud storage bucket could expose every record you have ever collected. If you encrypt them correctly, that same breach yields nothing useful to an attacker. The difference in outcome is enormous, and the difference in implementation effort is smaller than most developers expect.

Cryptography also matters for trust between systems, not just between systems and users. Modern applications are built from many components: microservices, third-party APIs, message queues, background workers, and cloud storage. Each connection between those components is a potential attack surface. Digital signatures let you verify that a message from your payment processor actually came from your payment processor. Authenticated encryption lets you confirm that a message stored in a queue has not been tampered with between the time it was written and the time it was read. These are not edge cases. They are everyday requirements for production software.

The regulatory environment has also made cryptography a practical necessity, not just a best practice. Regulations like GDPR in Europe, HIPAA in the United States, and PCI DSS for payment card data all include specific requirements around encryption and data protection.[2] Failing to meet those requirements can result in significant fines and legal liability. Understanding how to implement cryptography correctly is increasingly a professional requirement for developers working in regulated industries.

Finally, cryptography matters because the threat landscape keeps evolving. Algorithms that were considered secure ten years ago may be deprecated or broken today. Quantum computing is advancing in ways that will eventually threaten some of the asymmetric algorithms currently in widespread use. Staying current with cryptographic standards is not a one-time task. It is an ongoing responsibility, and it starts with understanding the fundamentals well enough to recognize when something needs to change.

A concrete example of the stakes: In 2012, the social network LinkedIn suffered a breach that exposed approximately 6.5 million password hashes. Those hashes were generated using unsalted SHA-1, an algorithm that was already considered weak for password storage at the time. Within days, the majority of those hashes had been cracked. In 2016, it emerged that the actual breach had exposed 117 million accounts. Had LinkedIn used a proper password hashing algorithm like bcrypt, the cracking effort would have been orders of magnitude more difficult, and the damage to users would have been dramatically reduced.[3]

The lesson from examples like LinkedIn is not that cryptography is impossibly hard to get right. It is that the cost of getting it wrong is very high, and the tools to get it right are readily available. Python's cryptographic ecosystem gives you those tools. This book shows you how to use them.

What You'll Learn in This Book

This book is organized to take you from foundational concepts to practical implementation, and then into more advanced patterns that you will encounter in real production systems. Each chapter builds on the previous ones, but the structure also allows you to jump to specific topics when you need a reference for a particular problem you are solving right now.

Here is a summary of what each part of the book covers:

  • Cryptography Fundamentals (Chapter 1): The core concepts you need to understand before writing any code. This includes the difference between encryption and hashing, how symmetric and asymmetric encryption work at a conceptual level, and how to think about threat models so you can choose the right tool for a given situation.
  • The Python Cryptography Ecosystem (Chapter 2): A practical guide to the libraries available in Python, how to choose between them, and how to set up your development environment correctly from the start.
  • Symmetric Encryption in Practice (Chapter 3): How to implement AES encryption, which modes of operation to use and why, and real-world examples of encrypting data at rest.
  • Hashing and Data Integrity (Chapter 4): How cryptographic hashing works, how to hash passwords securely using modern algorithms, and how to use hashes to verify that data has not been tampered with.
  • Asymmetric Encryption and Key Exchange (Chapter 5): RSA encryption, key generation and management, and the key exchange protocols that make secure communication possible.
  • Digital Signatures and Authentication (Chapter 6): How to sign data to prove its origin and integrity, and how to verify signatures in your applications.
  • Cryptographic Key Management (Chapter 7): The often-overlooked challenge of storing, rotating, and distributing cryptographic keys securely.
  • Authenticated Encryption and AEAD (Chapter 8): How to combine encryption and authentication in a single operation, and why this matters for preventing certain classes of attacks.
  • Building Secure Communication Systems (Chapter 9): TLS/SSL, certificate management, secure APIs, and end-to-end encryption patterns.
  • Advanced Cryptographic Patterns (Chapter 10): An introduction to more advanced topics like secret sharing, zero-knowledge proofs, and homomorphic encryption.
  • Testing and Auditing Cryptographic Code (Chapter 11): How to test your cryptographic implementations, assess vulnerabilities, and conduct security code reviews.

Throughout the book, the emphasis is on working code. Every major concept is accompanied by Python examples that you can run, adapt, and integrate into your own projects. The examples use real libraries and real patterns, not simplified pseudocode that glosses over the details that actually matter in production.

By the end of this book, you will be able to make confident decisions about which cryptographic tools to use for a given problem. You will understand the reasoning behind those decisions, not just the mechanics. You will know how to avoid the most common implementation mistakes, and you will have a reference you can return to when you encounter new cryptographic challenges in your work.

You will also develop an important habit of mind: thinking about security as a design concern, not an afterthought. The best time to think about how you will protect sensitive data is before you write the code that handles it, not after a breach has already occurred. This book will help you build that habit by consistently connecting implementation decisions to the security properties they provide or fail to provide.

One thing this book does not do is cover every cryptographic algorithm that has ever existed. The field is vast, and many older algorithms are now deprecated or broken. Instead, the focus is on the algorithms and patterns that are currently recommended for production use, with clear explanations of why certain older approaches should be avoided. Security is not just about knowing what to do. It is equally about knowing what not to do.

How to Use This Guide

This book is designed to work for two different kinds of readers. If you are new to cryptography and want to build a solid foundation before writing any code, reading from beginning to end is the right approach. The chapters are sequenced so that each one builds on the concepts introduced before it. Starting with the fundamentals and working forward will give you the most complete understanding of how the pieces fit together.

If you already have some exposure to cryptographic concepts and are looking for practical guidance on a specific problem, you can use the book as a reference. Each chapter is largely self-contained, with cross-references to related sections when a concept from another chapter is relevant. The appendix at the back of the book includes a quick-reference algorithm comparison chart and a collection of common code snippets that you can use as starting points for your own implementations.

Here are some suggested reading paths based on common goals:

  • If you need to implement password storage right now: Start with Chapter 1 for context, then go directly to Chapter 4 (Hashing and Data Integrity), specifically the section on secure password hashing.
  • If you are building an API that needs to verify the identity of callers: Read Chapter 6 (Digital Signatures and Authentication) and Chapter 9 (Building Secure Communication Systems).
  • If you need to encrypt files or database fields: Start with Chapter 3 (Symmetric Encryption in Practice) and Chapter 8 (Authenticated Encryption and AEAD).
  • If you are setting up a new project and want to get the foundations right: Read Chapters 1 and 2 first, then proceed based on your specific requirements.
  • If you are reviewing existing code for security issues: Chapter 11 (Testing and Auditing Cryptographic Code) is your starting point, with references back to earlier chapters for specific algorithms and patterns.

The code examples in this book are written for Python 3.10 and later. All examples use libraries that are actively maintained and widely used in production environments. Where a library has multiple ways to accomplish the same task, the examples show the approach that is currently recommended by the library's documentation and the broader security community. Deprecated or discouraged approaches are noted explicitly, with explanations of why they should be avoided.

Each chapter ends with a brief summary of the key points covered and a list of the most important takeaways. These summaries are useful for review after you have read a chapter, and they can also serve as a quick orientation if you are jumping into a chapter without reading the ones before it. Pay attention to the warnings and pitfall callouts throughout the text. These highlight the specific mistakes that developers most commonly make when implementing cryptographic features, and avoiding them is just as important as understanding the correct approach.

The code in this book is meant to be read alongside the explanations, not just copied and pasted. Understanding why a particular function is called with particular arguments, or why a certain parameter is set to a specific value, is what separates a developer who can implement cryptography correctly from one who can only reproduce examples they have seen before. Take the time to understand each example before moving on. That investment will pay off when you encounter a situation that does not match any example exactly, which is most of the time in real development work.

Finally, treat this book as a starting point, not a final authority. The cryptographic landscape changes over time. Algorithms get deprecated, new vulnerabilities are discovered, and best practices evolve. The resources listed throughout the book, including the documentation for the libraries covered and the publications of organizations like NIST (the National Institute of Standards and Technology), are the authoritative sources for current recommendations. Developing the habit of checking those sources when you are making security decisions is one of the most valuable things you can take away from this book.

Prerequisites and Setup

This book assumes you are comfortable writing Python code. You do not need to be an expert, but you should be able to read and write functions, work with classes, handle exceptions, and use common data structures like lists and dictionaries without difficulty. If you are still learning the basics of Python syntax, spending some time with a Python fundamentals resource before diving into this book will make the experience much smoother.

Beyond Python itself, some familiarity with the following concepts will be helpful, though not strictly required:

  • Basic networking concepts: Understanding what a client and server are, what HTTP and HTTPS mean, and how data travels across a network will help you follow the chapters on secure communication.
  • Command-line usage: You should be comfortable running commands in a terminal, installing packages with pip, and navigating your file system from the command line.
  • Working with bytes in Python: Cryptographic operations work on raw bytes, not strings. If you are not familiar with Python's bytes and bytearray types, or with encoding and decoding between strings and bytes, it is worth reviewing those concepts before you start. The first chapter includes a brief refresher on this topic.
  • Basic understanding of web applications: For the chapters on secure APIs and communication, a general understanding of how web requests and responses work will be useful.

No prior knowledge of cryptography is assumed. The book introduces every cryptographic concept it uses, starting from the fundamentals in Chapter 1. If you have some background in cryptography already, you may find the early chapters move quickly, but they also establish the specific terminology and mental models that the rest of the book builds on, so they are worth at least skimming.

To follow along with the code examples, you will need a working Python environment. Here is the recommended setup:

  1. Python 3.10 or later: Download and install from python.org if you do not already have it. You can check your current version by running python --version or python3 --version in your terminal.
  2. A virtual environment: It is strongly recommended to create a dedicated virtual environment for the code in this book. This keeps the libraries you install isolated from your system Python and other projects. Create one with python -m venv crypto-env and activate it with source crypto-env/bin/activate on macOS/Linux or crypto-env\Scripts\activate on Windows.
  3. The cryptography library: This is the primary library used throughout the book. Install it with pip install cryptography. It is maintained by the Python Cryptographic Authority (PyCA) and is widely considered the best general-purpose cryptographic library for Python.[4]
  4. PyCryptodome: Some chapters also use PyCryptodome, which provides a different interface and some additional algorithms. Install it with pip install pycryptodome. Note that PyCryptodome and the older PyCrypto library are not compatible; if you have PyCrypto installed, remove it first.

A note on operating systems: the examples in this book have been tested on macOS and Linux. They should work on Windows as well, but some command-line instructions may differ slightly. If you are on Windows and encounter issues, using the Windows Subsystem for Linux (WSL) is a reliable way to get a Linux-compatible environment without leaving Windows.

Security is also a concern in your development environment itself. When working with cryptographic code, be careful about where you store test keys and credentials. Even in a development context, it is a good habit to keep sensitive material out of your source code and out of version control. The chapters on key management will cover this in detail, but the habit starts now. Consider creating a .env file for any secrets your test code needs, and add it to your .gitignore immediately.

If you want to verify that your environment is set up correctly before you start Chapter 1, run the following quick test in your Python interpreter. It imports the core library and generates a small random key, which confirms that the library is installed and functioning:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
import os

# Generate 32 random bytes (a 256-bit key)
key = os.urandom(32)
print(f"Generated key (hex): {key.hex()}")
print("Environment is ready.")

If that runs without errors and prints a hex string followed by the confirmation message, your environment is ready to go. If you see an import error, double-check that you have activated your virtual environment and that the cryptography package was installed into it. With that in place, you are ready to start building a genuine understanding of cryptography and how to apply it in your Python applications.

Back to contents

Notes

Introduction

  1. 1. Identity Theft Resource Center, "'2023 Annual Data Breach Report," ' ITRC, 2024
  2. 2. European Parliament, "'General Data Protection Regulation (GDPR)," ' Official Journal of the European Union, 2016
  3. 3. "Hunt," Troy. 'LinkedIn's Password Hashing Failure.' Troy Hunt Blog, 2012
  4. 4. Python Cryptographic Authority, 'cryptography,' PyPI

This is the end of the free sample. The full book has 11 chapters.

Want this book written for you?

Tell us your goals and background, and get your own version of this book, tailored by AI to you.

User avatar
User avatar
User avatar
User avatar
User avatar
9,198 books created by readers like you
As seen on:
Product HuntRedditMediumDEV

Benefits of AI-tailored books

Read one book, not ten:
all the Cryptography knowledge you need, gathered into a single book.
Save days of learning:
tell us your goals, choose your topics, and the whole book is built around them.
Learn effortlessly:
Cryptography book written for your specific background and expertise.
Understand at a glance:
includes charts, tables, timelines, checklists, decision trees, and more.
Stay current:
written the day you order it, not years ago.
Trust what you read:
every book is checked for accuracy, with real research when your subject needs it.

Create your unique book in 3 steps

1. Select your focus

Select the focus of your Cryptography book and share your background

Your Cryptography book focus
2. Personalize your book

Specify your goals and choose sub-topics to include

3. Get your tailored book

Your book is ready in 10 minutes. Read it online, download as EPUB or PDF, or send to Kindle.

Frequently asked questions

What is TailoredRead?

TailoredRead creates complete, full-length nonfiction ebooks, written specifically for you. Tell us what you want to learn and why, and TailoredRead writes you a complete ebook on it, with charts, tables, and diagrams throughout. Read it online, on Kindle, or on any e-reader, or download it as a PDF or EPUB. Every book is written fresh the day you order it.

How is the book tailored to me?

Before anything is written, you answer a few short questions about your goals, your background, and the topics you care about. Your book is then planned around your answers: written at your level, focused on your goals, and covering the topics you chose, instead of the one-size-fits-all book a store sells everyone.

Will it read like generic AI content?

No. Your book isn't a chat transcript: it's planned chapter by chapter before a single word is written, told in a clear book voice, and explains ideas visually with charts, tables, and diagrams. After writing, every book goes through an editorial pass that polishes chapters so the book reads consistent from start to finish. Judge for yourself: browse thousands of sample books on our Explore Books page.

How accurate is the content?

Our AI first checks whether your subject needs live research. Niche and fast-moving subjects are researched before writing, and the book plan and chapters are grounded in what it finds. After writing, every book goes through a quality pass that checks its facts and consistency, and researched books list their sources in a Notes section at the back.

How long is the book?

You choose the length: Comprehensive (250-300 pages), Detailed (150-200 pages), Essential (70-100 pages), or Short (30-50 pages).

Does the book include visuals?

Yes. Every book includes charts, tables, and diagrams: timelines, checklists, step-by-step guides, decision trees, comparison tables, matrices, and bar charts. A typical book includes dozens of these visual elements.

Can I read it on Kindle? What formats can I download?

Yes. Every book can be read in our online reader or downloaded as a PDF or EPUB. The EPUB can be opened with Kindle, Apple Books, Kobo, and any e-reader. The Commercial and Author licenses also include an editable Word (DOCX) and Markdown download.

How much does it cost?

About the price of a regular ebook. The exact price depends on your book's length and complexity, from $2 for the shortest books to $35 for the most comprehensive, and it's shown when you review your book, before you commit to anything. Each book is a one-time purchase, yours to keep, no subscription. Licenses that let you share, teach, or publish your book range from $35.99 to $49.99.

Can I preview the book before purchasing?

Before you pay, you'll see what your book will cover: the title, a detailed description, the estimated length, and the complete chapter-by-chapter table of contents, so you know what you're getting before you decide. The full text itself is written after you purchase.

How long does it take to create a book?

About 10 minutes. You can start reading the opening chapters while the rest is still being written.

Personalize and buy this book

Get your personalized version, tailored by AI to your goals, background, and interests