Skip to content

capstone.utils.crypto

Description: This module provides reusable cryptographic utilities.

compute_sha256(for_file_path)

Compute the SHA-256 hash of a file.

Parameters:

Name Type Description Default
for_file_path str

Path to the file.

required

Returns:

Type Description
str

The SHA-256 hash as a hexadecimal string.

Source code in capstone/utils/crypto.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def compute_sha256(for_file_path: str) -> str:
    """
    Compute the SHA-256 hash of a file.

    Args:
        for_file_path: Path to the file.

    Returns:
        The SHA-256 hash as a hexadecimal string.
    """
    hash_sha256 = sha256()
    try:
        with open(for_file_path, "rb") as f:
            for chunk in iter(lambda: f.read(CHUNK_SIZE), b""):
                hash_sha256.update(chunk)
        if IS_VERBOSE():
            logger.info(f"SHA-256 for {for_file_path}: {hash_sha256.hexdigest()}")
        return hash_sha256.hexdigest()
    except FileNotFoundError:
        logger.error(f"File not found: {for_file_path}")
        raise
    except Exception as e:
        logger.error(f"Error computing SHA-256 for {for_file_path}: {e}")
        raise

validate_sha256(sha256)

Validates the SHA-256 checksum format.

Parameters:

Name Type Description Default
sha256 str

The SHA-256 checksum to validate.

required

Returns:

Name Type Description
bool bool

True if the checksum is valid, False otherwise.

Source code in capstone/utils/crypto.py
69
70
71
72
73
74
75
76
77
78
79
80
81
def validate_sha256(sha256: str) -> bool:
    """Validates the SHA-256 checksum format.

    Args:
        sha256 (str): The SHA-256 checksum to validate.

    Returns:
        bool: True if the checksum is valid, False otherwise.
    """
    import re

    pattern = r"^[a-fA-F0-9]{64}$"
    return bool(re.match(pattern, sha256))

verify_sha256(for_file_path, expected_hash)

Verify the SHA-256 hash of a file against an expected hash.

Parameters:

Name Type Description Default
for_file_path str

Path to the file.

required
expected_hash str

The expected SHA-256 hash as a hexadecimal string.

required

Returns: True if the computed hash matches the expected hash, False otherwise.

Source code in capstone/utils/crypto.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def verify_sha256(for_file_path: str, expected_hash: str) -> bool:
    """
    Verify the SHA-256 hash of a file against an expected hash.

    Args:
        for_file_path: Path to the file.
        expected_hash: The expected SHA-256 hash as a hexadecimal string.
    Returns:
        True if the computed hash matches the expected hash, False otherwise.
    """

    try:
        # get the computed hash
        computed_hash = compute_sha256(for_file_path)
        # normalize to lowercase for comparison
        if computed_hash.lower() == expected_hash.lower():
            if IS_VERBOSE():
                logger.info(f"Hash match for {for_file_path}")
            return True
        else:
            logger.warning(
                f"Hash mismatch for {for_file_path}: expected {expected_hash}, got {computed_hash}"
            )
            return False
    except Exception as e:
        logger.error(f"Error verifying SHA-256 for {for_file_path}: {e}")
        return False