Skip to content

Base keys

The cryptographic keys involved for the secretbox API, for the hash API and for key derivation are very similar. All of them are derived from a base key class.

Because they inherit from BaseKey class, HashKeys, SecretBoxKeys and Masterkeys have the following properties:

  • They encapsulate a 32-byte key that's allocated using guarded heap memory.
  • A random key can be generated using the gen class method.
  • They implement the Buffer protocol and can by used as bytes-like objects.
  • They can be exported as a str using the __str__ method (base64 encoding is used).
  • They can be written to a file using the writeto method.
  • They can be read from a file using the read_from method.

class BaseKey

Base class for keys used in symmetric cryptography (e.g., hashing, encryption).

Users should not instantiate this class directly. Instead, use one of the subclasses.

The memory to store the key is allocated using guarded heap allocations, similar to what is done in libsodium.

BaseKey implements the buffer protocol, allowing it to be used as a bytes-like object.

__bool__()

Returns True if the key is not zero, False otherwise.

Returns:

  • bool

    True if the key is not zero, False otherwise.

__init__(b=None)

Initialize the BaseKey with an optional bytes object.

Parameters:

  • b (bytes | None, default: None ) –

    A bytes object representing the key. If None, a zero key will be created.

Raises:

  • MemoryError

    If memory allocation for the key fails.

  • TypeError

    If the provided key is not a bytes object.

  • ValueError

    If the provided key is not 32 bytes long.

__str__()

Returns a base64-encoded representation of the key.

Returns:

  • str

    A string representing the key in base64 encoding.

gen() classmethod

Generate a new BaseKey with random bytes.

Returns:

  • Self

    A new instance of BaseKey.

is_zero()

Checks if the key is the zero key.

Returns:

  • bool

    True if the key is zero, False otherwise.

read_from(reader) classmethod

Create a key from a reader.

Parameters:

  • reader (Reader) –

    A reader object that supports the read method.

Returns:

  • Self

    A new instance of BaseKey read from the provided reader.

Raises:

  • TypeError

    If the provided reader does not have a 'read' method.

  • ValueError

    If the read data is not 32 bytes long.

writeto(out)

Write the key to a writer.

Parameters:

  • out (Writer) –

    A writer object that supports the write method.

Returns:

  • int

    The number of bytes written, which should be 32.

Raises:

  • TypeError

    If the provided writer does not have a 'write' method.

zero() classmethod

Generate a new BaseKey initialized to zero.

Returns:

  • Self

    A new instance of BaseKey initialized to zero.