Skip to content

operations

get_hash_from_str(input_str=None, encoding='utf-8')

Return a hashed version of an input string.

Parameters:

Name Type Description Default
input_str str

The string to hash

None
encoding str

The character encoding to use

'utf-8'

Returns

(str): A hashed representation of `input_str`

Raises

ValueError: When input validation fails
Exception: A generic `Exception` when converting string to hash fails
Source code in src/red_utils/std/hash_utils/operations.py
def get_hash_from_str(input_str: str = None, encoding: str = "utf-8") -> str:
    """Return a hashed version of an input string.

    Params:
        input_str (str): The string to hash
        encoding (str): The character encoding to use

    Returns
    -------
        (str): A hashed representation of `input_str`

    Raises
    ------
        ValueError: When input validation fails
        Exception: A generic `Exception` when converting string to hash fails
    """
    if not input_str:
        raise ValueError("Missing input string")

    if not encoding:
        raise ValueError("Missing encoding")

    if not isinstance(input_str, str):
        try:
            input_str: str = str(input_str)

        except Exception as exc:
            raise Exception(
                f"Unhandled exception converting input string ({type(input_str)}) to str()"
            )

    try:
        hash = hashlib.md5(input_str.encode(encoding)).hexdigest()

    except Exception as exc:
        raise Exception(
            f"Unhandled exception converting string to hash. Details: {exc}"
        )

    return hash