Hybrid encryption in python

Igor Filatov
2 min readJun 14, 2022

--

Theory

As we all know there are two main types of encryption: symmetric and asymmetric.

Symmetric encryption uses a single key to encrypt and decrypt.

😃 Symmetric encryption is a fast technique.

😕 Less secured due to the usage of a single key for encryption.

Symmetric encryption

While asymmetric encryption encrypts and decrypts the data using two separate yet mathematically connected cryptographic keys.

😃 Much safer as two keys are involved in encryption and decryption.

😕 Asymmetric encryption is slower in terms of speed.

Asymmetric encryption

But what if you want to have the best from two worlds?

We can use so called hybrid encryption.

Hybrid encryption

Each time we send our data a new symmetric key is generated and encrypted with the public key. We send the encrypted data along with the symmetric key. When the data is received, we can decrypt the symmetric key with the private key and then decrypt the data itself.

😃 Asymmetric encryption is applied only to the symmetric key which has a constant size.

😃 The data size can vary but its encryption is fast.

Practice

Imagine that we need to send some data in JSON format over a local network that has no SSL.

Firstly we need to install a couple of packages.

pip install rsa cryptography
  1. Generate public + private keypair and share the private key with the receiver (a one-time thing)
  2. Generate a symmetric key
  3. Encrypt our data with the symmetric key
  4. Encrypt the symmetric key with the public key
  5. Encode the data and the symmetric key with base64
  6. Send the data along with the encrypted symmetric key
  7. Receive
  8. Decode the data and the symmetric key from base64
  9. Decrypt the symmetric key with the private key
  10. Decrypt data with the symmetric key

In this case we used 2048 bit RSA keys. You can choose from 1024, 2048 or 4096 bits depending on your use case. The private key can be stored at the client side either as a .PEM file or as a config variable.

--

--

Igor Filatov

Biomedical and software engineer dreaming about a better future. Currently living in Stockholm.