os_helper.hash_utils module

Hashing Utilities

A content hash turns any string, file, or folder into a short, fixed-length fingerprint: the same input always produces the same fingerprint, and two different inputs almost never collide. That single property answers three everyday questions: is this file the one I already downloaded (compare fingerprints instead of full bytes), have these two folders diverged (compare their folder hash), and can I use a file’s own content as its cache key (a name that never needs inventing and never goes stale).

hash_string(), hashfile(), and hashfolder() compute that fingerprint with RIPEMD-160 (BLAKE2b as a fallback where RIPEMD-160 is unavailable), always as a 40-character hex string regardless of which engine ran. This is content hashing, not password hashing: there is no salting and no key-stretching, so never use these for storing or checking passwords (see CREDENTIALS_MANAGEMENT.md).

Usage example

>>> import os_helper as osh
>>> osh.hash_string("hello")[:8]
'108f07b8'
>>> len(osh.hash_string("hello"))
40

Author

Warith HARCHAOUI, https://linkedin.com/in/warith-harchaoui

os_helper.hash_utils.hash_string(s, size=-1)[source]

Generate a hash of a given string and optionally returns a truncated version.

Parameters:
  • s (str) – The input string to hash.

  • size (int, optional) – If positive, truncates the hash to the specified length. Defaults to -1 (no truncation).

Returns:

The hashed string, optionally truncated.

Return type:

str

Example

>>> isinstance(hash_string("example"), str)
True
>>> len(hash_string("example"))
40
>>> len(hash_string("example", size=8))
8

Note

The exact digest depends on the underlying hash engine (RIPEMD-160 when available, BLAKE2b truncated to 20 bytes otherwise). The output length stays 40 hex characters either way.

os_helper.hash_utils.hashfile(path, hash_content=True, date=False)[source]

Generate a hash for a file’s content and/or its last modification date.

Parameters:
  • path (str) – The path to the file to hash.

  • hash_content (bool, optional) – If True, includes the file’s content in the hash (default: True).

  • date (bool, optional) – If True, includes the current date in the hash (default: False).

Returns:

The resulting hash of the file as a 40-character hex string.

Return type:

str

os_helper.hash_utils.hashfolder(path, hash_content=True, hash_path=False, date=False)[source]

Generate a hash for the contents of a folder and/or its path.

Parameters:
  • path (str) – The path to the folder to hash.

  • hash_content (bool, optional) – If True, includes the folder’s contents in the hash (default: True).

  • hash_path (bool, optional) – If True, includes the folder’s path in the hash (default: False).

  • date (bool, optional) – If True, includes the current date in the hash (default: False).

Returns:

The resulting hash of the folder and/or its contents as a 40-character hex string.

Return type:

str