Encrypting Data

Encrypting data with Fast File Encryption is straightforward and secure. All encryption operations are performed using a public RSA key, allowing you to share the encrypted files without exposing any private secrets.

You can encrypt:

  • Entire files and store them at a new destination

  • Raw in-memory data (bytes)

  • Streams (e.g., file-like objects or sockets)

Below is a quick example demonstrating how to encrypt a file:

>>> import fast_file_encryption as ffe
>>> from pathlib import Path
>>> original_file = Path('original_file.txt')
>>> original_file.write_text('Hello world!')
>>> encryptor = ffe.Encryptor(ffe.read_public_key(Path('public.pem')))
>>> encrypted_file = Path('encrypted_file.ffe')
>>> encryptor.copy_encrypted(
...     original_file,
...     encrypted_file,
...     meta={'my-meta': 1},
...     add_source_metadata=True
... )

Tip

When encrypting multiple files, reuse the same Encryptor instance. Internally, it caches the public key hash to avoid recalculating it for each file.

class fast_file_encryption.Encryptor(public_key)

The Encryptor class provides all core methods to securely encrypt byte sequences, files, and data streams.

Parameters:

public_key (RSAPublicKey) – The RSA public key used for encryption.

save_encrypted(source_data, destination, meta=None)

Encrypt a small byte buffer and store the result in a file.

Parameters:
  • source_data (bytes) – The in-memory data to encrypt.

  • destination (pathlib.Path) – Target path for the encrypted file. It is recommended to use the .ffe suffix.

  • meta (dict[str, any]) – Optional metadata dictionary stored alongside the encrypted data.

copy_encrypted(source, destination, meta=None, add_source_metadata=False)

Encrypt a file and write the result to a new location.

Parameters:
  • source (pathlib.Path) – Path to the unencrypted input file.

  • destination (pathlib.Path) – Path to the output file (typically ending in .ffe).

  • meta (dict[str, any]) – Optional dictionary with custom metadata.

  • add_source_metadata (bool) –

    If set to True, the following metadata will be added automatically unless overridden:

    • file_path

    • file_name

    • file_size

    • created

    • modified

Raises:

DataTooLargeError – Raised if the file size exceeds 10 TB.

stream_encrypted(source_io, destination_io, meta=None)

Encrypt data read from a stream and write it to another stream.

For small streams (less than ~4 KiB), the encryption is performed inline. Larger streams are encrypted using a chunked format.

Parameters:
  • source_io (io.BufferedIOBase) – Open input stream (must implement read()).

  • destination_io (io.BufferedIOBase) – Open output stream (must implement write()).

  • meta (dict[str, any]) – Optional metadata dictionary.

Decrypting Data →