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 cryptography.io.

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)
print(token.hex())

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

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

674141414141426555704e5a6e423947
333562524c504b333751745a47576432
3266305a6a33356c3645304838425446
316e5a58627850634741425f30545576
6b637956526e30664d75523337325261
776a543375785a677a64434353527142
61516e7446766f326f6d4a6c4d313363
84449776f4a673d

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