Skip to content

Secure Utilities

hash_str(val, algorithm=HashAlgoEnum.sha256)

Hash a string using a specified hash algorithm.

Parameters:

Name Type Description Default
val (str | bytes, required)

The value to be hashed.

required
algorithm HashAlgoEnum | str

The hash algorithm to use. Defaults to HashAlgoEnum.sha256.

sha256

Returns:

Name Type Description
str str

The hexadecimal representation of the digest.

Source code in src/potato_util/secure.py
@validate_call
def hash_str(
    val: str | bytes, algorithm: HashAlgoEnum | str = HashAlgoEnum.sha256
) -> str:
    """Hash a string using a specified hash algorithm.

    Args:
        val       (str | bytes       , required): The value to be hashed.
        algorithm (HashAlgoEnum | str, optional): The hash algorithm to use. Defaults to `HashAlgoEnum.sha256`.

    Returns:
        str: The hexadecimal representation of the digest.
    """

    if isinstance(val, str):
        val = val.encode("utf-8")

    if isinstance(algorithm, str):
        algorithm = HashAlgoEnum(algorithm.strip().lower())

    _hash = hashlib.new(algorithm.value)
    _hash.update(val)

    _hash_val = _hash.hexdigest()
    return _hash_val