Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/hash.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2019-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """OpenSSL implementation Hash algorithms."""
9
10 # Used security modules
11
12 from math import ceil
13
14 from cryptography.hazmat.primitives import hashes
15
16 from ..exceptions import SPSDKError
17 from ..utils.misc import Endianness
18 from ..utils.spsdk_enum import SpsdkEnum
19
20
21 class EnumHashAlgorithm(SpsdkEnum):
22 """Hash algorithm enum."""
23
24 SHA1 = (0, "sha1", "SHA1")
25 SHA256 = (1, "sha256", "SHA256")
26 SHA384 = (2, "sha384", "SHA384")
27 SHA512 = (3, "sha512", "SHA512")
28 MD5 = (4, "md5", "MD5")
29 SM3 = (5, "sm3", "SM3")
30
31
32 def get_hash_algorithm(algorithm: EnumHashAlgorithm) -> hashes.HashAlgorithm:
33 """For specified name return hashes algorithm instance.
34
35 :param algorithm: Algorithm type enum
36 :return: instance of algorithm class
37 :raises SPSDKError: If algorithm not found
38 """
39 algo_cls = getattr(hashes, algorithm.label.upper(), None) # hack: get class object by name
40 if algo_cls is None:
41 raise SPSDKError(f"Unsupported algorithm: hashes.{algorithm.label.upper()}")
42
43 algo = algo_cls()
44 assert isinstance(algo, hashes.HashAlgorithm)
45 return algo
46
47
48 def get_hash_length(algorithm: EnumHashAlgorithm) -> int:
49 """For specified name return hash binary length.
50
51 :param algorithm: Algorithm type enum
52 :return: Hash length
53 :raises SPSDKError: If algorithm not found
54 """
55 return get_hash_algorithm(algorithm).digest_size
56
57
58 class Hash:
59 """SPSDK Hash Class."""
60
61 def __init__(self, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256) -> None:
62 """Initialize hash object.
63
64 :param algorithm: Algorithm type enum, defaults to EnumHashAlgorithm.SHA256
65 """
66 self.hash_obj = hashes.Hash(get_hash_algorithm(algorithm))
67
68 def update(self, data: bytes) -> None:
69 """Update the hash by new data.
70
71 :param data: Data to be hashed
72 """
73 self.hash_obj.update(data)
74
75 def update_int(self, value: int) -> None:
76 """Update the hash by new integer value as is.
77
78 :param value: Integer value to be hashed
79 """
80 data = value.to_bytes(length=ceil(value.bit_length() / 8), byteorder=Endianness.BIG.value)
81 self.update(data)
82
83 def finalize(self) -> bytes:
84 """Finalize the hash and return the hash value.
85
86 :returns: Computed hash
87 """
88 return self.hash_obj.finalize()
89
90
91 def get_hash(data: bytes, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256) -> bytes:
92 """Return a HASH from input data with specified algorithm.
93
94 :param data: Input data in bytes
95 :param algorithm: Algorithm type enum
96 :return: Hash-ed bytes
97 :raises SPSDKError: If algorithm not found
98 """
99 hash_obj = hashes.Hash(get_hash_algorithm(algorithm))
100 hash_obj.update(data)
101 return hash_obj.finalize()