Simple encryption-at-rest with key rotation support for Python.

Related tags

Cryptographykeyringpy
Overview

keyring

Simple encryption-at-rest with key rotation support for Python.

keyring: Simple encryption-at-rest with key rotation support for Python.

N.B.: keyring is not for encrypting passwords--for that, you should use something like bcrypt. It's meant for encrypting sensitive data you will need to access in plain text (e.g. storing OAuth token from users). Passwords do not fall in that category.

This package is completely independent from any storage mechanisms; the goal is providing a few functions that could be easily integrated with any ORM.

Installation

Add package to your requirements.txt or:

pip install keyring

Usage

Encryption

By default, AES-128-CBC is the algorithm used for encryption. This algorithm uses 16 bytes keys, but you're required to use a key that's double the size because half of that keys will be used to generate the HMAC. The first 16 bytes will be used as the encryption key, and the last 16 bytes will be used to generate the HMAC.

Using random data base64-encoded is the recommended way. You can easily generate keys by using the following command:

$ dd if=/dev/urandom bs=32 count=1 2>/dev/null | openssl base64 -A
qUjOJFgZsZbTICsN0TMkKqUvSgObYxnkHDsazTqE5tM=

Include the result of this command in the value section of the key description in the keyring. Half this key is used for encryption, and half for the HMAC.

Key size

The key size depends on the algorithm being used. The key size should be double the size as half of it is used for HMAC computation.

  • aes-128-cbc: 16 bytes (encryption) + 16 bytes (HMAC).
  • aes-192-cbc: 24 bytes (encryption) + 24 bytes (HMAC).
  • aes-256-cbc: 32 bytes (encryption) + 32 bytes (HMAC).

About the encrypted message

Initialization vectors (IV) should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; it is important to remember that an attacker must not be able to predict ahead of time what a given IV will be.

With that in mind, keyring uses base64(hmac(unencrypted iv + encrypted message) + unencrypted iv + encrypted message) as the final message. If you're planning to migrate from other encryption mechanisms or read encrypted values from the database without using keyring, make sure you account for this. The HMAC is 32-bytes long and the IV is 16-bytes long.

Keyring

Keys are managed through a keyring--a short python Dictionary describing your encryption keys. The keyring must be a Dictionary object mapping numeric ids of the keys to the key values. A keyring must have at least one key. For example:

{
  "1": "uDiMcWVNTuz//naQ88sOcN+E40CyBRGzGTT7OkoBS6M=",
  "2": "VN8UXRVMNbIh9FWEFVde0q7GUA1SGOie1+FgAKlNYHc="
}

The id is used to track which key encrypted which piece of data; a key with a larger id is assumed to be newer. The value is the actual bytes of the encryption key.

Key Rotation

With keyring you can have multiple encryption keys at once and key rotation is fairly straightforward: if you add a key to the keyring with a higher id than any other key, that key will automatically be used for encryption when objects are either created or updated. Any keys that are no longer in use can be safely removed from the keyring.

It's extremely important that you save the keyring id returned by encrypt(); otherwise, you may not be able to decrypt values (you can always decrypt values if you still possess all encryption keys).

If you're using keyring to encrypt database columns, it's recommended to use a separated keyring for each table you're planning to encrypt: this allows an easier key rotation in case you need (e.g. key leaking).

N.B.: Keys are hardcoded on these examples, but you shouldn't do it on your code base. You can retrieve keyring from environment variables if you're deploying to Heroku and alike, or deploy a JSON file with your configuration management software (e.g. Ansible, Puppet, Chef, etc).

Basic usage of keyring

๐Ÿ”’ Vco48O95YC4jqj44MheY8zFO2NLMPp/KILiUGbKxHvAwLd2/AN+zUG650CJzogttqnF1cGMFb//Idg4+bXoRMQ== #=> ๐Ÿ”‘ 1 #=> ๐Ÿ”Ž c39ec9729dbacd45cecd5ea9a60b15b50b0cc857 # STEP 2: Decrypted message using encryption key defined by keyring id. decrypted = encryptor.decrypt(encrypted, keyringId) print(f'โœ‰๏ธ {decrypted}') #=> โœ‰๏ธ super secret">
from keyring import Keyring;

keys = { '1': "uDiMcWVNTuz//naQ88sOcN+E40CyBRGzGTT7OkoBS6M=" }
encryptor = Keyring(keys, { "digest_salt": "salt-n-pepper" })

# STEP 1: Encrypt message using latest encryption key.
encrypted, keyringId, digest = encryptor.encrypt("super secret")
print(f'๐Ÿ”’ {encrypted}')
print(f'๐Ÿ”‘ {keyringId}')
print(f'๐Ÿ”Ž {digest}')
#=> ๐Ÿ”’ Vco48O95YC4jqj44MheY8zFO2NLMPp/KILiUGbKxHvAwLd2/AN+zUG650CJzogttqnF1cGMFb//Idg4+bXoRMQ== 
#=> ๐Ÿ”‘ 1
#=> ๐Ÿ”Ž c39ec9729dbacd45cecd5ea9a60b15b50b0cc857

# STEP 2: Decrypted message using encryption key defined by keyring id.
decrypted = encryptor.decrypt(encrypted, keyringId)
print(f'โœ‰๏ธ {decrypted}')
#=> โœ‰๏ธ super secret

Change encryption algorithm

You can choose between AES-128-CBC, AES-192-CBC and AES-256-CBC. By default, AES-128-CBC will be used.

To specify the encryption algorithm, set the encryption option. The following example uses AES-256-CBC.

", })">
from keyring import Keyring

keys = { "1": "uDiMcWVNTuz//naQ88sOcN+E40CyBRGzGTT7OkoBS6M=" }
encryptor = Keyring(keys, {
  "encryption": "aes-256-cbc",
  "digest_salt": "
   
    "
   ,
})

Exchange data with Ruby

If you use Ruby, you may be interested in https://github.com/fnando/attr_keyring, which is able to read and write messages using the same format.

Exchange data with Node.js

If you use Node.js, you may be interested in https://github.com/fnando/keyring-node, which is able to read and write messages using the same format.

Development

After checking out the repo, run pip install -r requirements.dev.txt to install dependencies. Then, run pytest to run the tests.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/dannluciano/keyring-python. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Icon

Icon made by Icongeek26 from Flaticon is licensed by Creative Commons BY 3.0.

Code of Conduct

Everyone interacting in the keyring projectโ€™s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

Acknowledgments

Inspired:

Thanks to IFPI for pay my salary!

IFPI

Owner
Dann Luciano
Dann Luciano
A simple graphical interface for encrypting sentences

A simple graphical interface for encrypting sentences

Marcus Vinรญcius Ribeiro Andrade 1 Oct 09, 2021
Kyrie Eleison - The best and unique way to encrypt some data or a file safely

Encrypt your important data and files easily and safely with Kyrie Eleison.

Billy 39 Oct 27, 2022
How to setup a multi-client ethereum Eth1-Eth2 merge testnet

Mergenet tutorial Let's set up a local eth1-eth2 merge testnet! Preparing the setup environment In this tutorial, we use a series of scripts to genera

Diederik Loerakker 24 Jun 17, 2022
Small utility to encrypt and decrypt messages

Safe Safe is a small utility to encrypt and decrypt messages using a pair of public and private keys. Installation You need to have GPG installed in y

Gustavo Eguez 2 Dec 21, 2021
A repository for Algogenous Smart Contracts created on the Algorand Blockchain.

Smart Contacts This Repository is dedicated to code for Alogrand Smart Contracts using Choice Coin. Read Docs for how to implement Algogenous Smart Co

Choice Coin 3 Dec 20, 2022
A simple Ethereum mining pool

A simple getWork pool for ethereum mining Payouts are still manual. TODO: write payouts when someone mines 10 blocks. Also, make the submit actually

93 Oct 05, 2022
A discord bot to crop an NFT image living on the Solana blockchain.

NFT Discord Cropper This discord bot crops an NFT in your set measures by getting it through the .cache file which has been used to make a candy machi

Rude Golems 7 Mar 21, 2022
Generate simple encrypted messages!

Premio's Shift is a very simple text encryption, you can use it to send secret messages to your friends. Table of Content Table of Content How it work

Peterson Adami Candido 3 Aug 06, 2021
Stai Beta Of Staiking Chain - Food, Water And Electricity - Worldwide

Stai Beta Of Staiking Chain - Food, Water And Electricity - Worldwide

STATION-I 2 Feb 05, 2022
FileGuard - File crypter and packing utility

FILEGUARD FILEGUARD is a file crypter and packing utility. This project was orig

11 Nov 28, 2022
Vhost password decrypt for python

vhost_password_decrypt Where is symkey.dat Windows๏ผšC:\ProgramData\VMware\vCenterServer\cfg\vmware-vpx\ssl\symkey.dat Linux๏ผš/etc/vmware-vpx/ssl/symkey.

Jing Ling 152 Dec 22, 2022
Powerful Tool to encrypt and decrypt files using AES.

AEScryptor Tool Description Encrypt and Decrypt files with AES-128 (16bytes key). AES mode = CFB (cipher Feedback) security = super safe! Usage [1] Ch

5 Jan 12, 2022
Python binding to the Networking and Cryptography (NaCl) library

PyNaCl: Python binding to the libsodium library PyNaCl is a Python binding to libsodium, which is a fork of the Networking and Cryptography library. T

Python Cryptographic Authority 941 Jan 04, 2023
Linear encryption software programmed with python

Echoder linear encryption software programmed with python How does it work? The text in the text section runs a function with two keys entered keys mu

Emre Orhan 4 Dec 20, 2021
Hasher Hash, Compare and Verify your files Translations

Hasher Hash, Compare and Verify your files Translations In order to translate Hasher to a language you must add a folder with the language abbreviatio

Jeyson Flores 14 Apr 01, 2022
Tool to compare smart contracts source code

smartdiffer Tool to compare smart contracts source code. Heavily relies on API of Etherscan and Diffchecker. Installation pip install smartdiffer API

Roman Moskalenko 23 Nov 16, 2022
SHIBgreen is a cryptocurrency forked from Chia and uses the Proof of Space and Time consensus algorithm

SHIBgreen is a cryptocurrency forked from Chia and uses the Proof of Space and Time consensus algorithm

13 Jul 13, 2022
SSEPy: Implementation of searchable symmetric encryption in pure Python

SSEPy: Implementation of searchable symmetric encryption in pure Python Searchable symmetric encryption, one of the research hotspots in applied crypt

33 Dec 05, 2022
This python module can analyse cryptocurrency news for any number of coins given and return a sentiment. Can be easily integrated with a Trading bot to keep an eye on the news.

Python script that analyses news headline or body sentiment and returns the overall media sentiment of any given coin. It can take multiple coins an

185 Dec 22, 2022
XMRiGUI is free and open-source crypto miner for Linux. It uses XMRig for mining and GTK3 for GUI.

XMRiGUI is free and open-source crypto miner for Linux. It uses XMRig for mining and GTK3 for GUI.

29 Jul 07, 2022