Cryptography getting started

Martin McBride, 2020-02-22
Tags installing anaconda
Categories cryptography

This article is part of a series on the Python cryptography library.

The cryptography module can be installed using pip, like this:

pip install cryptography

If you use Anaconda, you can also install cryptography in the usual way with conda.

Building the module yourself

Both pip and conda download a pre-built executable from a repository. There is, at least theoretically, a possibility of an attacker hacking the repository and replacing the original executable with their own doctored version, that might contain back doors.

If your application requires a high degree of security, you should consider building the library yourself. Instructions for doing this are included on the official cryptography module website at

Checking the module

You can check that the module is installed correctly using this simple program that creates a key then encodes and decodes a message:

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()

# Create a Fernet instance with the key
cipher = Fernet(key)

# Encrypt a message
message = "Message to be encrypted".encode('utf-8')
token = cipher.encrypt(message)

# Decrypt the cipertext
decoded = cipher.decrypt(token)

The line print(token.hex()) should print the encrypted message, something like:


The encrypted data will be different every time, because it contains random elements.

The line print(decoded) prints the result of decrypting the token. It should be:

b'Message to be encrypted'

We will look at this code in more detail in the Fernet encryption section.

Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function plot functools generator gif gradient html image processing imagesurface immutable object index input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or path positional parameter print pure function radial gradient range recursion reduce rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020