Skip to content

Hashing

from cydrogen import Hash, HashKey

DATA = b"data to hash"

# simple
d1 = Hash(data=DATA).digest()  # uses the zero key, default context
d2 = Hash(key="6kNVkds/wu9auUhPhMXzvwfsdW5Sq6SnYA095fBl+yU=", data=DATA).digest()

# Hash and HashKey classes
key = HashKey.gen()             # generate a random hash key
hasher = Hash(key=key)          # default context, default digest size
hasher.update(DATA)
hash_value = hasher.digest()    # 16 bytes

# you can choose the size of the digest
hasher = Hash(ctx="example", digest_size=32)    # uses the zero key
hasher.update(DATA)
assert len(hasher.digest()) == 32

class HashKey

Bases: BaseKey

HashKey represents a crypto key for hashing.

Hashing operations may be performed using a key to prevent dictionary attacks. If you don't need to prevent dictionary attacks, you can use the empty key for hashing.

__bool__()

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

Returns:

  • bool

    True if the key is not zero, False otherwise.

__init__(key=None)

Initialize the HashKey with an optional key. If the key is None, an empty key is created.

It is not possible to initialize a HashKey from another concrete key type like MasterKey, SignKeyPair, SignPublicKey, or SignSecretKey.

Parameters:

  • key (str | bytes | Self | Buffer | None, default: None ) –

    A bytes-like object, a base64 encoded string, or None for an empty key.

Raises:

  • TypeError

    If the key is of an unsupported type.

  • ValueError

    If the key is not a valid bytes-like object or base64 encoded string.

__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.

hasher(data=None, ctx=None, digest_size=16)

Returns a hasher object initialized with the key.

Parameters:

  • data (bytes | Buffer | None, default: None ) –

    Optional initial data to hash.

  • ctx (Context | str | bytes | Buffer | None, default: None ) –

    Optional context for the hash operation.

  • digest_size (int, default: 16 ) –

    Size of the desired digest in bytes.

Returns:

  • Hash

    A Hash object initialized with the key, the context and optional data.

Raises:

  • ValueError

    If the digest size is not within the valid range (16 to 65535 bytes) or if the context is invalid.

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.

class Hash

Hash is a class for computing cryptographic hashes.

All attributes are initialized in the constructor and are immutable after that.

Attributes:

  • ctx (Context) –

    The context for the hash operation.

  • key (HashKey) –

    The key used for hashing.

  • digest_size (int) –

    The size of the hash digest in bytes.

  • block_size (int) –

    The block size used in the hash algorithm.

__init__(data=None, *, ctx=None, digest_size=16, key=None)

Initialize the hasher.

Parameters:

  • data (bytes | Buffer | None, default: None ) –

    Optional initial data to hash.

  • ctx (str | bytes | Context | Buffer | None, default: None ) –

    Optional context for the hash operation.

  • digest_size (int, default: 16 ) –

    Size of the desired digest in bytes (default is 16).

  • key (str | bytes | HashKey | Buffer | None, default: None ) –

    Optional HashKey to use for hashing.

Raises:

  • ValueError

    If the digest size is not within the valid range (16 to 65535 bytes) or if the context is invalid.

  • RuntimeError

    If the hash has already been finalized.

  • TypedError

    If the key is of an unsupported type.

digest()

Finalize the hash and return the digest.

Returns:

  • bytes

    The computed hash digest.

hexdigest()

Finalize the hash and return the digest as a hex string.

Returns:

  • str

    The hexadecimal representation of the hash digest.

update(data)

Update the hash with new data.

Parameters:

  • data (bytes | Buffer) –

    Data to hash, as a bytes-like object.

Returns:

  • Self

    The Hash object itself, allowing for method chaining.

Raises:

update_from(fileobj, chunk_size=8192)

Read data from a file-like/path-like object and update the hash.

Parameters:

  • fileobj (str | PathLike | BinaryIO) –

    A file-like object or path-like object to read data from.

  • chunk_size (int, default: 8192 ) –

    Size of the chunks to read from the file.

Returns:

  • Self

    The Hash object itself, allowing for method chaining.

Raises:

  • ValueError

    If fileobj_or_path is None.

  • TypeError

    If fileobj_or_path is not a path-like object or a file-like object.

write(data)

Write data to the hash.

Parameters:

  • data (bytes | Buffer) –

    Data to hash, as a bytes-like object.

Returns:

  • int

    The number of bytes written to the hash.

Raises:

hash_file(fileobj, ctx=None, digest_size=16, key=None, chunk_size=8192)

Compute the hash of a binary file-like object.

Parameters:

  • fileobj (str | PathLike | BinaryIO) –

    A file-like object or path-like object to read data from.

  • ctx (str | bytes | Context | Buffer | None, default: None ) –

    Optional context for the hash operation.

  • digest_size (int, default: 16 ) –

    Size of the desired digest in bytes (default is 16).

  • key (str | bytes | HashKey | Buffer | None, default: None ) –

    Optional HashKey to use for hashing.

  • chunk_size (int, default: 8192 ) –

    Size of the chunks to read from the file.

Returns:

  • bytes

    The computed hash digest as bytes.

Raises:

  • ValueError

    If fileobj is None or if the digest size is not within the valid range (16 to 65535 bytes) or if the context is invalid.

  • TypeError

    If fileobj is not a path-like object or a file-like object, or if key is of an unsupported type.