Skip to content

Commit cab35a5

Browse files
impl: stream into sha256 (#15)
* impl: stream into sha256 Signed-off-by: William Woodruff <william@trailofbits.com> * test_impl: add a JSON loads test Signed-off-by: William Woodruff <william@trailofbits.com> * fixup! impl: stream into sha256 --------- Signed-off-by: William Woodruff <william@trailofbits.com> Co-authored-by: Facundo Tuesca <facundo.tuesca@trailofbits.com>
1 parent 4c1ddd3 commit cab35a5

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/pypi_attestation_models/_impl.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
import binascii
99
from base64 import b64decode, b64encode
10-
from hashlib import sha256
1110
from typing import TYPE_CHECKING, Annotated, Any, Literal, NewType
1211

1312
import rfc8785
@@ -17,6 +16,7 @@
1716
from cryptography.hazmat.primitives import serialization
1817
from pydantic import BaseModel
1918
from pydantic_core import ValidationError
19+
from sigstore._utils import _sha256_streaming
2020
from sigstore.models import Bundle, LogEntry
2121

2222
if TYPE_CHECKING:
@@ -116,9 +116,14 @@ class AttestationPayload(BaseModel):
116116
@classmethod
117117
def from_dist(cls, dist: Path) -> AttestationPayload:
118118
"""Create an `AttestationPayload` from a distribution file."""
119+
with dist.open(mode="rb", buffering=0) as io:
120+
# Replace this with `hashlib.file_digest()` once
121+
# our minimum supported Python is >=3.11
122+
digest = _sha256_streaming(io).hex()
123+
119124
return AttestationPayload(
120125
distribution=dist.name,
121-
digest=sha256(dist.read_bytes()).hexdigest(),
126+
digest=digest,
122127
)
123128

124129
def sign(self, signer: Signer) -> Attestation:

test/test_impl.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,4 @@ def test_attestation_payload(self) -> None:
160160
expected = f'{{"digest":"{payload.digest}","distribution":"{payload.distribution}"}}'
161161

162162
assert bytes(payload) == bytes(expected, "utf-8")
163+
assert json.loads(bytes(payload)) == json.loads(expected)

0 commit comments

Comments
 (0)