File Hashing
The file hashing module provides utilities for generating various types of file hashes and checksums for data integrity verification.
Module Overview
Hash Management Functions - Fixed Version Provides standardized hash functions that actually exist and work properly
- siege_utilities.files.hashing.calculate_file_hash(file_path)[source]
Alias for get_file_hash with SHA256 - for backward compatibility.
- Return type:
- siege_utilities.files.hashing.generate_sha256_hash_for_file(file_path)[source]
Generate SHA256 hash for a file - chunked reading for large files.
Deprecated since version 3.19.0: Use
calculate_file_hash()orget_file_hash()instead. Will be removed in v4.0.0.SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files.
- Parameters:
file_path – Path to the file (str or Path object)
- Returns:
SHA256 hash as hexadecimal string
- Raises:
FileNotFoundError – If file does not exist or is not a file
PathSecurityError – If path fails security validation
OSError – If file cannot be read
- Return type:
Example
>>> hash_val = generate_sha256_hash_for_file("data.txt")
- siege_utilities.files.hashing.get_file_hash(file_path, algorithm='sha256')[source]
Generate hash for a file using specified algorithm.
SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files.
- Parameters:
file_path – Path to the file (str or Path object)
algorithm – Hash algorithm to use (‘sha256’, ‘md5’, ‘sha1’, etc.)
- Returns:
Hash as hexadecimal string
- Raises:
FileNotFoundError – If file does not exist or is not a file
PathSecurityError – If path fails security validation
OSError – If file cannot be read
ValueError – If algorithm is not supported
- Return type:
Example
>>> hash_val = get_file_hash("data.txt", "sha256")
- siege_utilities.files.hashing.get_quick_file_signature(file_path)[source]
Generate a quick file signature using file stats + partial hash Faster for change detection, not cryptographically secure
SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files.
- Parameters:
file_path – Path to the file
- Returns:
Quick signature string (‘missing’, fallback stat string, or hash)
- Raises:
PathSecurityError – If path fails security validation
Exception – If both primary and fallback signature generation fail (logged before re-raise)
- Return type:
Example
>>> sig = get_quick_file_signature("data.txt") >>> get_quick_file_signature("/etc/passwd")
- Security Changes:
Now validates paths to block path traversal
Blocks access to sensitive system files
- siege_utilities.files.hashing.verify_file_integrity(file_path, expected_hash, algorithm='sha256')[source]
Verify file integrity by comparing with expected hash.
SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files (through get_file_hash).
- Parameters:
file_path – Path to the file
expected_hash – Expected hash value
algorithm – Hash algorithm used
- Returns:
True if file matches expected hash, False if hash does not match
- Raises:
FileNotFoundError – If file does not exist
PathSecurityError – If path fails security validation
OSError – If file cannot be read
- Return type:
Example
>>> expected = "abc123..." >>> if verify_file_integrity("data.txt", expected): ... print("File integrity verified")
Functions
- siege_utilities.files.hashing.get_file_hash(file_path, algorithm='sha256')[source]
Generate hash for a file using specified algorithm.
SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files.
- Parameters:
file_path – Path to the file (str or Path object)
algorithm – Hash algorithm to use (‘sha256’, ‘md5’, ‘sha1’, etc.)
- Returns:
Hash as hexadecimal string
- Raises:
FileNotFoundError – If file does not exist or is not a file
PathSecurityError – If path fails security validation
OSError – If file cannot be read
ValueError – If algorithm is not supported
- Return type:
Example
>>> hash_val = get_file_hash("data.txt", "sha256")
- siege_utilities.files.hashing.calculate_file_hash(file_path)[source]
Alias for get_file_hash with SHA256 - for backward compatibility.
- Return type:
- siege_utilities.files.hashing.verify_file_integrity(file_path, expected_hash, algorithm='sha256')[source]
Verify file integrity by comparing with expected hash.
SECURITY: This function validates paths to prevent path traversal attacks and access to sensitive system files (through get_file_hash).
- Parameters:
file_path – Path to the file
expected_hash – Expected hash value
algorithm – Hash algorithm used
- Returns:
True if file matches expected hash, False if hash does not match
- Raises:
FileNotFoundError – If file does not exist
PathSecurityError – If path fails security validation
OSError – If file cannot be read
- Return type:
Example
>>> expected = "abc123..." >>> if verify_file_integrity("data.txt", expected): ... print("File integrity verified")
Usage Examples
Basic file hashing:
import siege_utilities
# Calculate MD5 hash
md5_hash = siege_utilities.get_file_hash('document.pdf', 'md5')
print(f"MD5: {md5_hash}")
# Calculate SHA256 hash
sha256_hash = siege_utilities.get_file_hash('document.pdf', 'sha256')
print(f"SHA256: {sha256_hash}")
# Calculate SHA1 hash
sha1_hash = siege_utilities.get_file_hash('document.pdf', 'sha1')
print(f"SHA1: {sha1_hash}")
Generic hashing with algorithm selection:
# Use generic hash function
hash_value = siege_utilities.get_file_hash('data.csv', algorithm='sha256')
print(f"Hash: {hash_value}")
# Available algorithms: md5, sha1, sha256, sha512
algorithms = ['md5', 'sha1', 'sha256']
hashes = {}
for algo in algorithms:
hashes[algo] = siege_utilities.get_file_hash('large_file.dat', algorithm=algo)
for algo, hash_val in hashes.items():
print(f"{algo.upper()}: {hash_val}")
File integrity verification:
# Verify file integrity
original_hash = "a1b2c3d4e5f6..."
is_valid = siege_utilities.verify_file_integrity('document.pdf', original_hash, 'sha256')
if is_valid:
print("File integrity verified!")
else:
print("File may be corrupted or modified")
Batch processing:
import os
# Process multiple files
files_to_hash = ['file1.txt', 'file2.txt', 'file3.txt']
hash_results = {}
for filename in files_to_hash:
if os.path.exists(filename):
hash_results[filename] = {
'md5': siege_utilities.get_file_hash(filename, 'md5'),
'sha256': siege_utilities.get_file_hash(filename, 'sha256')
}
# Display results
for filename, hashes in hash_results.items():
print(f"\n{filename}:")
print(f" MD5: {hashes['md5']}")
print(f" SHA256: {hashes['sha256']}")
Unit Tests
The file hashing module has comprehensive test coverage:
✅ test_file_hashing.py - All file hashing tests pass
Test Coverage:
- MD5 hash calculation
- SHA1 hash calculation
- SHA256 hash calculation
- Generic hash function with algorithm selection
- File integrity verification
- Error handling for missing files
- Performance with large files
- Hash consistency across multiple calls
Test Results: All file hashing tests pass successfully with comprehensive coverage.