Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sigstore/hashes.py: 65%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

23 statements  

1# Copyright 2023 The Sigstore Authors 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14 

15""" 

16Hashing APIs. 

17""" 

18 

19import rekor_types 

20from cryptography.hazmat.primitives import hashes 

21from cryptography.hazmat.primitives.asymmetric.utils import Prehashed 

22from pydantic import BaseModel 

23from sigstore_protobuf_specs.dev.sigstore.common.v1 import HashAlgorithm 

24 

25from sigstore.errors import Error 

26 

27 

28class Hashed(BaseModel, frozen=True): 

29 """ 

30 Represents a hashed value. 

31 """ 

32 

33 algorithm: HashAlgorithm 

34 """ 

35 The digest algorithm uses to compute the digest. 

36 """ 

37 

38 digest: bytes 

39 """ 

40 The digest representing the hash value. 

41 """ 

42 

43 def _as_hashedrekord_algorithm(self) -> rekor_types.hashedrekord.Algorithm: 

44 """ 

45 Returns an appropriate `hashedrekord.Algorithm` for this `Hashed`. 

46 """ 

47 if self.algorithm == HashAlgorithm.SHA2_256: 

48 return rekor_types.hashedrekord.Algorithm.SHA256 

49 raise Error(f"unknown hash algorithm: {self.algorithm}") 

50 

51 def _as_prehashed(self) -> Prehashed: 

52 """ 

53 Returns an appropriate Cryptography `Prehashed` for this `Hashed`. 

54 """ 

55 if self.algorithm == HashAlgorithm.SHA2_256: 

56 return Prehashed(hashes.SHA256()) 

57 raise Error(f"unknown hash algorithm: {self.algorithm}") 

58 

59 def __str__(self) -> str: 

60 """ 

61 Returns a str representation of this `Hashed`. 

62 """ 

63 return f"{HashAlgorithm(self.algorithm)}:{self.digest.hex()}"