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
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
Pogramme de chiffrement et déchiffrement césar d'un message en python3.

Chiffrement Cesar En Python3 Pogramme de chiffrement et déchiffrement césar d'un message en python3. Explication du chiffrement César avec complexité

Malik Makkes 1 Mar 26, 2022
RSI Algorithmic Trading with Python

In this repository you can see my first algorithhmic trading script. I use 5 cryptocurrencies: Bitcoin (BTC), Ethereum (ETH), Bitcoin Cash (BCH), Litecoin (LTC) and Chainlink (LINK).

Jon Aldekoa 4 Mar 16, 2022
Create and finder all address wallet bitcoin and check balance , transaction

BTCCrackWallet Create and finder all address wallet bitcoin and check balance , transaction bitcoin wallet generator generated address wallet , public

MMDRZA 11 Nov 26, 2022
Marketplace but with cryptocurrencies only.

MoneroMarket Marketplace but with cryptocurrencies only. MoneroMarket was created as a way to be able to use cryptocurrencies as an actual currency to

Janoher 35 Jan 01, 2023
Taishang Credential With Interactive Badges

结合数字徽章的交互式区块链证书 DApp 1 项目简介 DID 与 VC 一直是区块链研究的重要领域,也是区块链落地的重要基础,从「传统证书」到基于DID的VC证书是证书体系范式转移的重要第一步。 但是,在迈出第一步之后我们可以进行更加丰富的尝试,例如尝试将不可转移的徽章与可转移的权益与证书相结合,

1 Nov 07, 2021
Python FFI bindings for libsecp256k1 (maintained)

secp256k1-py Python FFI bindings for libsecp256k1 (an experimental and optimized C library for EC operations on curve secp256k1). Previously maintaine

Rusty Russell 29 Dec 29, 2022
Encrypt decrypt files - Programmed in Python | PySimpleGUI

Crypter Programmed in Python | PySimpleGUI If you like it give it a star How it works Crypter program use Fernet for encryption. Fernet guarantees tha

Adrijan 11 Jun 18, 2022
Bitcoin & Lightning Container Manager for facilitating development tools

Torch-cli Bitcoin & Lightning Container Manager for facilitating development too

Gray Finance 3 Aug 22, 2022
Blockchain Python Implementation

Blockchain Python Implementation

0918nobita 2 Nov 21, 2021
Python Steganography data hiding in image

Python-Steganography Python Steganography data hiding in image data encryption and decryption im here you have to import stepic module 1.open CMD 2.ty

JehanKandy 10 Jul 13, 2022
Cryptocurrency application that displays instant cryptocurrency prices and reads prices with the Google Text-to-Speech library.

📈 Cryptocurrency Price App 💰 ◽ Cryptocurrency application that displays instant cryptocurrency prices and reads prices with the Google Text-to-Speec

Furkan Mert 2 Nov 08, 2021
Modeval (or Modular Eval) is a modular and secure string evaluation library that can be used to create custom parsers or interpreters.

modeval Modeval (or Modular Eval) is a modular and secure string evaluation library that can be used to create custom parsers or interpreters. Basic U

2 Jan 01, 2022
SDU experiment of introduction to the cryptography

Lab 01 (2 hrs): Programming Basics Program 1: Type Hint, String, Bytes, Hex, Base64 Lab 02 (4 hrs): Classical Cryptography Part 1 (3 hrs): Program 1:

1 Jan 03, 2022
BlockVis - Create beautiful visualizations of Bitcoin Blockheaders

BlockVis Create beautiful visualizations of Bitcoin Blockheaders How to run To r

Egge 2 Jan 05, 2022
Coins farmer for dank memer

Created by TheRider#5308 [feel free to drop by to talk]. Note to some Dank Memer staff reading this: Nah I don't self bot, already got banned for that

Siddhant Kumar 3 Nov 10, 2021
Python Cryptocurrency with stealth addresses

Python Cryptocurrency with stealth addresses. Goal is to have create a cryptocurency that hides transactions totally. I.E. Cant see ammount sent, to who, or from who.

3 Aug 04, 2022
Python implementation of a blockchain.

The goal of this project is to explain and to make clearer how is a blockchain structured at the very core. It's not built with the intention to replicate an advanced blockchain like Bitcoin or Ether

Rahul raikwar 5 Jan 28, 2022
Crypto Stats and Tweets Data Pipeline using Airflow

Crypto Stats and Tweets Data Pipeline using Airflow Introduction Project Overview This project was brought upon through Udacity's nanodegree program.

Matthew Greene 1 Nov 24, 2021
Crypto Portfolio Clustering with and without optimization techniques (elbow method, PCA).

Crypto Portfolio Clustering Crypto Portfolio Clustering with and without optimization techniques (elbow method, PCA). Analysis This is an anlysis of c

David L 0 Feb 18, 2022