API reference

interface

This module owns the client interface within the main class CryptoFactory.

class crypto_factory.interface.CryptoFactory

Client interface for Crypto-Factory.

It provides following features access:

  • Crypto services management (See factory module.)
  • Abstraction methods for encryption; rely on underneath Crypto services (See providers module.)
  • Tagging mechanism
  • Advanced method(s) such as rotate to migrate encrypted data to another Crypto service
  • Crypto utilities such as generate random keys and strings, inspect tags or encoding functions (See utilities module.)
  • Built-in Crypto providers for direct use of defined encryption algorithms (See providers module.)
  • Crypto templates for building your own encryption algorithms (See providers module.)
decrypt(data, mode=None, tag_strict=False)

Abstraction method for symmetric decryption.

Check if tag is matching selected Crypto service ‘mode’ (if ‘tag_strict’ enabled). Remove tag before calling decrypt method of selected Crypto service.

Parameters:
  • data (str or bytes) – Encrypted data (to decrypt).
  • mode (str or int) – Crypto service identifier (‘sid’ in factory).
  • tag_strict (bool) – Enforce tag validation (False by default). If True, compare data tag with Crypto service tag.
Returns:

decrypted data as str

Raises:

CryptoFactoryError – An exception is raised if an error occurs. Check error message for details.

encrypt(data, mode, tag=True)

Abstraction method for symmetric encryption.

Call encrypt method of selected Crypto service. Will add a ‘tag’ to encrypted ‘data’ before returning result if tag=True.

Parameters:
  • data (str or bytes) – Plain data (to encrypt).
  • mode (str or int) – Crypto service identifier (‘sid’ in factory).
  • tag (bool) – Add the Crypto service tag to ‘data’ if True (default). If Crypto service has tagging disabled (no ‘tag’ on register), this parameter will be skipped (set to False).
Returns:

encrypted data as str

Raises:

CryptoFactoryError – An exception is raised if an error occurs. Check error message for details.

rotate(data=None, from_modes=None, to_mode=None, tag_strict=False, tag=True)

Advanced method to ‘rotate’ encrypted data from one or more Crypto services to a target one. It can be used for keys rotation, migration of existing data to a new Crypto service, …

Based on decrypt and encrypt methods, will provide same tag options.

Parameters:
  • data (str or bytes) – Encrypted data (to rotate).
  • from_modes (str or list) – Source Crypto service identifier(s).
  • to_mode (str or int) – Target Crypto service identifier.
  • tag_strict (bool) – Enforce tag validation (see decrypt method).
  • tag (bool) – Add the Crypto service tag (see encrypt method).
Returns:

encrypted data as str (to target Crypto service format)

Raises:

CryptoFactoryError – An exception is raised if an error occurs. In particular when no ‘from_modes’ methods are able to decrypt data. Check error message for details.

services

entry-point to Crypto services manager (See CryptoServicesManager class for details.)

utils

entry-point to Crypto utilities (See CryptoUtils class for details.)

factory

This module is responsible of managing Crypto providers through the CryptoServicesManager class.

class crypto_factory.factory.CryptoServicesManager

CryptoServiceManager is the “factory” class which will manage the Crypto providers and will handle calls from the client interface.

get(sid)

Call to a Crypto service instance

This method is called by abstraction methods from the client interface and should not be used directly.

Parameters:sid (str or int) – Crypto service identifier to call. (Equivalent to mode argument in client interface)
Returns:Crypto service builder class instance
Raises:CryptoFactoryError – If the Crypto service is not registered.
get_mode(sid)

Get Crypto service instance by its identifier

get_mode_tag(sid)

Get Crypto service tag by its identifier

get_tag_mode(tag)

Get Crypto service identifier by its tag

providers

Index of active Crypto services

register(config=None, sid=None, builder=None, tag=None)

Register and initialize a Crypto service using its builder class.

Parameters:
  • config (dict) – Crypto service parameters to initialize it (dict). Required keys/values are dependant to arguments needed by the Crypto service (ie: key, iv, …). Can also have id, builder and tag keys to replace following arguments.
  • sid (str or int) – Crypto service identifier to register with. (Equivalent to mode argument in client interface)
  • builder (class or str) –

    Crypto service builder as a child class of CryptoBuilder. Class name as str also supported for built-in providers.

    Note

    If builder=None, a null entry will be created for this service identifier. This is the method to use to deregister a service.

  • tag (str) – Crypto service tag as a string of characters (tag can be used as identifier on encrypted data). The tag will be formatted using normalize_tag method (from CryptoUtils class). “$” character is reserved as it is used as separator. (See API for details)
Returns:

sid or None Return sid if builder has been successfully registered and initialized as an available service. Return None if builder has not been initialized.

Raises:

CryptoFactoryError – If the Crypto service is unable to register or initialize, an error is raised. Check error message for details.

tags

Index of current tags associated to a Crypto services

providers

This module contains built-in Crypto builders and associated services.

class crypto_factory.providers.DummyServiceBuilder
Builder for DummyService:
For illustration purpose only (do NOT use it in production !!!)
specifications:
  • Surround data with label
static initialize(label=None)
service

alias of DummyService

class crypto_factory.providers.FernetServiceBuilder
Builder for FernetService:
Fernet implementation (secured)
specifications:
  • AES / CBC mode / PKCS7 padding
  • HMAC authentication with SHA256
  • 256 bits key (used for AES & HMAC)
  • random 128-bit IV
  • urlsafe Base64 encoding
  • string to bytes conversion in UTF-8

(https://cryptography.io/en/latest/fernet/)

static initialize(key=None)
service

alias of FernetService

class crypto_factory.providers.AESServiceBuilder
Builder for AESService:
AES-CBC-PKCS7 implementation
specifications:
  • AES / CBC mode / PKCS7 padding
  • key of different sizes (128, 192 or 256 bits)
  • random of fixed IV (16 bytes) support
  • optional prefix (fixed string)
  • optional random salt addition (salt_length in bytes)
  • standard or urlsafe base64 encoding
  • standard string encodings support
string format:
<random_IV: 16><prefix><salt><data>
initialize(key, iv=None, prefix=None, salt_length=None, urlsafe=None, encoding=None)

AESServiceBuilder initialisation

Parameters:
  • key (bytes) – key of 16, 24 or 32 bytes
  • iv (bytes) – fixed IV of 16 bytes If None, a random IV will be generated on each call and added to encrypted data.
  • prefix (str) – Optional string of data added to encrypted data.
  • salt_length (int) – Optional random value of ‘salt_length’ bytes added to encrypted data.
  • urlsafe (bool) – If True, use ‘urlsafe’ Base64 encoding. Else, use standard Base64. This apply to both key and iv values. Ensure same Base64 method has been used to generate them.
  • encoding (str) – Any supported Python encoding to use for Str / Bytes conversion. (See codecs for details)
Returns:

dict of parameters for AESService

Note

This provider can be sub-classed in order to define parameters default values. This would allow to design a specific AES implementation without the need to provide all parameters on each initialisation.

These parameters can bet set in the _defaults class attribute (dict). key parameter cannot be defined as defaults as it should always be provided from client.

example:

class MyAESBuilder(AESServiceBuilder):
    _defaults = dict(
        iv= None,
        prefix='MyAES-prefix',
        salt_length=24,
        urlsafe=False,
        encoding='utf-16',
    )
service

alias of AESService

utilities

This module provides the CryptoUtils class available within the Crypto-Factory interface through the utils property.

class crypto_factory.utils.CryptoUtils
static b64decode(s, urlsafe=True)
static b64encode(s, urlsafe=True)
classmethod compare_tag(value, tag)

Compare tag. Return True if tag in string (encrypted data), else False.

static data_bytes(data, encoding='utf-8', errors='strict')

Convert data to bytes using standard encoding values if data is str.

static data_string(data, encoding='utf-8', errors='strict')

Convert data to str using standard encoding values if data is bytes.

static generate_key(size=256, urlsafe=True)

Generate random keys (as bytes) of 128, 192, 256, or 512 bits size. (standard or urlsafe base64 encoded.)

classmethod generate_string(length=8, chars=None, tag=False)

Generate a random string value of ‘n’ valid characters.

Parameters:
  • length (int) – Number of characters to return.
  • chars (str) – Valid characters tu use. If None, will use any charaters from ascii_letters, digits & punctuation (from string library).
  • tag (bool) – If True, will use valid characters for tag. (take precedence on chars argument)
Returns:

str (None if length is not int)

static generate_tag()

Generate a unique tag (return a standard uuid4 as str)

classmethod get_tag(value)

Get tag from string (encrypted data)

classmethod normalize_tag(tag)

Normalize tag value

If tag is type int, will return its string representation (str).

If tag is type dict, will look for ‘tag’ key value ; then will validate string as str.

If tag is type str, will check if its characters are valid then return a normalized tag in upper format:

  • Valid characters are ascii letters, digits and punctuation in “!#(),-.:;<>?@[]_{|}”.
  • $” (used as separator), and other characters will be removed.
Parameters:tag (str or int or dict) – Value to normalize as ‘tag’.
Returns:normalized tag (upper str) OR None
classmethod remove_tag(value)

Remove tag from string (encrypted data)

valid_tag_chars = '!#(),-.:;<>?@[]_{|}abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

exceptions

This module provides the CryptoFactoryError Exception class.

exception crypto_factory.exceptions.CryptoFactoryError

Crypto-Factory exceptions class to simplify errors management in client interface.

templates

This module contains CryptoBuilder & CryptoService parent classes to use when designing a Crypto provider.

class crypto_factory.templates.CryptoBuilder

Template to design a Crypto Builder. Main purpose is to define an initialize method to assign to a Crypto Service.

This Crypto Service must be designated in the service class attribute.

By default, the initialize method will forward all parameters received by the register command as a dict. This method can be personalised to fulfill the needs of the implemented cryptography recipe.

All defined Crypto Builders must inherit from the CryptoBuilder class.

Example:

class MyBuilder(CryptoBuilder):
    service = MyService

    @staticmethod
    def initialize(key=None):
        ...
        cipher = MyCryptoRecipe(key)
        return cipher
Note:
See this warning on sensitive data in memory.
static initialize(**params)
service = None
class crypto_factory.templates.CryptoService(cipher)

Template to design a Crypto Service. Called by an associated builder, it must implement abstraction methods from the interface module (encrypt & decrypt).

By default, __init__ method will provide the cipher (config) built by the Crypto builder. It can be personalised to fulfill the needs of the implemented cryptography recipe.

All defined Crypto Services must inherit from the CryptoService class.

Example:

class MyService(CryptoService):

    def encrypt(self, data):
        ...
        enc = self.cipher.encrypt(data)
        return enc

    def decrypt(self, data):
        ...
        plain = self.cipher.decrypt(data)
        return plain
Note:
See this warning on sensitive data in memory.
decrypt(data)
encrypt(data)