Debian Codegraph @

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

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2020-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7 """Module for key generation and saving keys to file."""
8
9 import abc
10 import math
11 from abc import abstractmethod
12 from typing import Any, Optional
13
14 from cryptography.exceptions import InvalidSignature
15 from cryptography.hazmat.primitives.asymmetric import padding, rsa
16 from cryptography.hazmat.primitives.serialization import PublicFormat
17
18 from ..utils.misc import Endianness
19 from .hash import EnumHashAlgorithm, get_hash, get_hash_algorithm
20 from .types import SPSDKEncoding
21
22
23 class PublicKey(abc.ABC):
24 """SPSDK Public Key."""
25
26 key: Any
27
28 @property
29 @abc.abstractmethod
30 def signature_size(self) -> int:
31 """Size of signature data."""
32
33 @property
34 @abc.abstractmethod
35 def public_numbers(self) -> Any:
36 """Public numbers."""
37
38 @abc.abstractmethod
39 def verify_signature(
40 self, signature: bytes, data: bytes, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256
41 ) -> bool:
42 """Verify input data.
43
44 :param signature: The signature of input data
45 :param data: Input data
46 :param algorithm: Used algorithm
47 :return: True if signature is valid, False otherwise
48 """
49
50 @abc.abstractmethod
51 def export(self, encoding: SPSDKEncoding = SPSDKEncoding.NXP) -> bytes:
52 """Export key into bytes to requested format.
53
54 :param encoding: encoding type, default is NXP
55 :return: Byte representation of key
56 """
57
58 def key_hash(self, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256) -> bytes:
59 """Get key hash.
60
61 :param algorithm: Used hash algorithm, defaults to sha256
62 :return: Key Hash
63 """
64 return get_hash(self.export(), algorithm)
65
66 def __eq__(self, obj: Any) -> bool:
67 """Check object equality."""
68 return isinstance(obj, self.__class__) and self.public_numbers == obj.public_numbers
69
70 def __ne__(self, obj: Any) -> bool:
71 return not self.__eq__(obj)
72
73 @abstractmethod
74 def __repr__(self) -> str:
75 """Object representation in string format."""
76
77 @abstractmethod
78 def __str__(self) -> str:
79 """Object description in string format."""
80
81
82 # ===================================================================================================
83 # ===================================================================================================
84 #
85 # RSA Keys
86 #
87 # ===================================================================================================
88 # ===================================================================================================
89
90
91 class PublicKeyRsa(PublicKey):
92 """SPSDK Public Key."""
93
94 SUPPORTED_KEY_SIZES = [2048, 3072, 4096]
95
96 key: rsa.RSAPublicKey
97
98 def __init__(self, key: rsa.RSAPublicKey) -> None:
99 """Create SPSDK Public Key.
100
101 :param key: SPSDK Public Key data or file path
102 """
103 self.key = key
104
105 @property
106 def signature_size(self) -> int:
107 """Size of signature data."""
108 return self.key.key_size // 8
109
110 @property
111 def key_size(self) -> int:
112 """Key size in bits.
113
114 :return: Key Size
115 """
116 return self.key.key_size
117
118 @property
119 def public_numbers(self) -> rsa.RSAPublicNumbers:
120 """Public numbers of key.
121
122 :return: Public numbers
123 """
124 return self.key.public_numbers()
125
126 @property
127 def e(self) -> int:
128 """Public number E.
129
130 :return: E
131 """
132 return self.public_numbers.e
133
134 @property
135 def n(self) -> int:
136 """Public number N.
137
138 :return: N
139 """
140 return self.public_numbers.n
141
142 def export(
143 self,
144 encoding: SPSDKEncoding = SPSDKEncoding.NXP,
145 exp_length: Optional[int] = None,
146 modulus_length: Optional[int] = None,
147 ) -> bytes:
148 """Save the public key to the bytes in NXP or DER format.
149
150 :param encoding: encoding type, default is NXP
151 :param exp_length: Optional specific exponent length in bytes
152 :param modulus_length: Optional specific modulus length in bytes
153 :returns: Public key in bytes
154 """
155 if encoding == SPSDKEncoding.NXP:
156 exp_rotk = self.e
157 mod_rotk = self.n
158 exp_length = exp_length or math.ceil(exp_rotk.bit_length() / 8)
159 modulus_length = modulus_length or math.ceil(mod_rotk.bit_length() / 8)
160 exp_rotk_bytes = exp_rotk.to_bytes(exp_length, Endianness.BIG.value)
161 mod_rotk_bytes = mod_rotk.to_bytes(modulus_length, Endianness.BIG.value)
162 return mod_rotk_bytes + exp_rotk_bytes
163
164 return self.key.public_bytes(
165 SPSDKEncoding.get_cryptography_encodings(encoding), PublicFormat.PKCS1
166 )
167
168 def verify_signature(
169 self, signature: bytes, data: bytes, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256
170 ) -> bool:
171 """Verify input data.
172
173 :param signature: The signature of input data
174 :param data: Input data
175 :param algorithm: Used algorithm
176 :return: True if signature is valid, False otherwise
177 """
178 try:
179 self.key.verify(
180 signature=signature,
181 data=data,
182 padding=padding.PKCS1v15(),
183 algorithm=get_hash_algorithm(algorithm),
184 )
185 except InvalidSignature:
186 return False
187
188 return True
189
190 def __eq__(self, obj: Any) -> bool:
191 """Check object equality."""
192 return isinstance(obj, self.__class__) and self.public_numbers == obj.public_numbers
193
194 def __repr__(self) -> str:
195 return f"RSA{self.key_size} Public Key"
196
197 def __str__(self) -> str:
198 """Object description in string format."""
199 ret = f"RSA{self.key_size} Public key: \ne({hex(self.e)}) \nn({hex(self.n)})"
200 return ret