A Python port of the Invisible Internet Project (I2P)
1"""SHA256Generator — SHA-256 hash computation.
2
3Ported from net.i2p.crypto.SHA256Generator.
4Wraps Python's hashlib.sha256.
5"""
6
7import hashlib
8
9from i2p_crypto.hash_data import Hash
10
11
12class SHA256Generator:
13 """SHA-256 hash generator. Thread-safe (hashlib creates new state per call)."""
14
15 _instance: "SHA256Generator | None" = None
16
17 def __init__(self) -> None:
18 pass
19
20 @classmethod
21 def get_instance(cls) -> "SHA256Generator":
22 if cls._instance is None:
23 cls._instance = SHA256Generator()
24 return cls._instance
25
26 def calculate_hash(self, source: bytes, start: int = 0, length: int = -1) -> Hash:
27 """Calculate SHA-256 and return a Hash object."""
28 if length < 0:
29 length = len(source) - start
30 digest = hashlib.sha256(source[start : start + length]).digest()
31 return Hash(digest)
32
33 def calculate_hash_into(self, source: bytes, start: int, length: int,
34 out: bytearray, out_offset: int) -> None:
35 """Calculate SHA-256 into an existing buffer."""
36 digest = hashlib.sha256(source[start : start + length]).digest()
37 out[out_offset : out_offset + Hash.HASH_LENGTH] = digest
38
39 @staticmethod
40 def digest(data: bytes) -> bytes:
41 """Convenience: return raw 32-byte SHA-256 digest."""
42 return hashlib.sha256(data).digest()