nitrokey 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. {nitrokey-0.1.0 → nitrokey-0.2.0}/PKG-INFO +5 -3
  2. {nitrokey-0.1.0 → nitrokey-0.2.0}/pyproject.toml +8 -13
  3. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nk3/updates.py +3 -2
  4. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/lpc55.py +11 -12
  5. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/README.md +6 -0
  6. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/__init__.py +13 -0
  7. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/__init__.py +7 -0
  8. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/certificate.py +208 -0
  9. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/hash.py +107 -0
  10. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/hmac.py +24 -0
  11. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/keys.py +214 -0
  12. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/symmetric.py +76 -0
  13. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/types.py +69 -0
  14. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/exceptions.py +47 -0
  15. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/__init__.py +10 -0
  16. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/commands.py +525 -0
  17. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/error_codes.py +353 -0
  18. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/exceptions.py +58 -0
  19. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/interfaces/__init__.py +8 -0
  20. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/interfaces/usb.py +60 -0
  21. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/mcuboot.py +1779 -0
  22. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/memories.py +240 -0
  23. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/properties.py +868 -0
  24. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/protocol/__init__.py +8 -0
  25. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/protocol/base.py +16 -0
  26. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/protocol/bulk_protocol.py +119 -0
  27. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/misc.py +190 -0
  28. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/__init__.py +8 -0
  29. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/commands.py +1057 -0
  30. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/headers.py +181 -0
  31. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/images.py +367 -0
  32. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/sections.py +205 -0
  33. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/__init__.py +8 -0
  34. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/abstract.py +33 -0
  35. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/crypto/__init__.py +8 -0
  36. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/crypto/cert_blocks.py +334 -0
  37. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/crypto/rkht.py +110 -0
  38. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/exceptions.py +13 -0
  39. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/__init__.py +8 -0
  40. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/commands.py +34 -0
  41. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/device/__init__.py +8 -0
  42. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/device/base.py +73 -0
  43. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/device/usb_device.py +183 -0
  44. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/protocol/__init__.py +8 -0
  45. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/protocol/protocol_base.py +80 -0
  46. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/misc.py +260 -0
  47. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/lpc55_upload/utils/spsdk_enum.py +175 -0
  48. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52.py +4 -4
  49. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu-cc.proto +89 -0
  50. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_cc_pb2.py +53 -0
  51. nitrokey-0.2.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_cc_pb2.pyi +183 -0
  52. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport.py +11 -8
  53. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport_serial.py +64 -75
  54. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/init_packet_pb.py +10 -111
  55. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/manifest.py +26 -86
  56. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/exceptions.py +4 -1
  57. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/device_lister.py +12 -27
  58. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/enumerated_device.py +8 -6
  59. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/lister_backend.py +3 -1
  60. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/unix/unix_lister.py +4 -5
  61. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/lister_win32.py +38 -28
  62. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/structures.py +38 -27
  63. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_utils.py +0 -6
  64. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/admin_app.py +2 -0
  65. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/crc16.py +0 -54
  66. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_cc_pb2.py +0 -866
  67. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_trigger.py +0 -229
  68. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/model.py +0 -57
  69. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/nrfhex.py +0 -188
  70. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/package.py +0 -763
  71. nitrokey-0.1.0/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/signing.py +0 -256
  72. {nitrokey-0.1.0 → nitrokey-0.2.0}/LICENSES/Apache-2.0.txt +0 -0
  73. {nitrokey-0.1.0 → nitrokey-0.2.0}/LICENSES/MIT.txt +0 -0
  74. {nitrokey-0.1.0 → nitrokey-0.2.0}/README.md +0 -0
  75. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/__init__.py +0 -0
  76. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/_helpers.py +0 -0
  77. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nk3/__init__.py +0 -0
  78. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nk3/_bootloader.py +0 -0
  79. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nk3/_device.py +0 -0
  80. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nk3/secrets_app.py +0 -0
  81. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/nkpk.py +0 -0
  82. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/py.typed +0 -0
  83. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/__init__.py +0 -0
  84. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_base.py +0 -0
  85. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/__init__.py +0 -0
  86. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/README.md +0 -0
  87. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/__init__.py +0 -0
  88. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/__init__.py +0 -0
  89. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/__init__.py +0 -0
  90. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/unix/__init__.py +0 -0
  91. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/__init__.py +0 -0
  92. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_bootloader/nrf52_upload/lister/windows/constants.py +0 -0
  93. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_device.py +0 -0
  94. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/_exceptions.py +0 -0
  95. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/trussed/provisioner_app.py +0 -0
  96. {nitrokey-0.1.0 → nitrokey-0.2.0}/src/nitrokey/updates.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: nitrokey
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Nitrokey Python SDK
5
5
  Home-page: https://github.com/Nitrokey/nitrokey-sdk-py
6
6
  License: Apache-2.0 or MIT
@@ -14,13 +14,15 @@ Classifier: Programming Language :: Python :: 3.9
14
14
  Classifier: Programming Language :: Python :: 3.10
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Dist: crcmod (>=1.7,<2.0)
18
+ Requires-Dist: cryptography (>=42)
17
19
  Requires-Dist: ecdsa (>=0.19,<0.20)
18
20
  Requires-Dist: fido2 (>=1.1.2,<2.0.0)
19
- Requires-Dist: protobuf (>=3.17.3,<4.0.0)
21
+ Requires-Dist: hidapi (>=0.14,<0.15)
22
+ Requires-Dist: protobuf (>=5.26,<6.0)
20
23
  Requires-Dist: pyserial (>=3.5,<4.0)
21
24
  Requires-Dist: requests (>=2,<3)
22
25
  Requires-Dist: semver (>=3,<4)
23
- Requires-Dist: spsdk (>=2,<2.3)
24
26
  Requires-Dist: tlv8 (>=0.10,<0.11)
25
27
  Project-URL: Repository, https://github.com/Nitrokey/nitrokey-sdk-py
26
28
  Description-Content-Type: text/markdown
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [tool.poetry]
6
6
  name = "nitrokey"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "Nitrokey Python SDK"
9
9
  authors = ["Nitrokey <pypi@nitrokey.com>"]
10
10
  license = "Apache-2.0 or MIT"
@@ -25,11 +25,13 @@ semver = "^3"
25
25
  tlv8 = "^0.10"
26
26
 
27
27
  # lpc55
28
- spsdk = ">=2,<2.3"
28
+ crcmod = "^1.7"
29
+ cryptography = ">=42"
30
+ hidapi = "^0.14"
29
31
 
30
32
  # nrf52
31
33
  ecdsa = "^0.19"
32
- protobuf = "^3.17.3"
34
+ protobuf = "^5.26"
33
35
  pyserial = "^3.5"
34
36
 
35
37
  [tool.poetry.group.dev]
@@ -37,10 +39,13 @@ optional = true
37
39
 
38
40
  [tool.poetry.group.dev.dependencies]
39
41
  black = "^24.3"
42
+ fake-winreg = "^1.6"
40
43
  flake8 = "^7.1"
41
44
  isort = "^5.13.2"
42
45
  mypy = "^1.4"
46
+ types-protobuf = "^5.26"
43
47
  types-requests = "^2.32"
48
+ typing-extensions = "^4"
44
49
 
45
50
  [tool.black]
46
51
  target-version = ["py39"]
@@ -54,13 +59,3 @@ mypy_path = "stubs"
54
59
  show_error_codes = true
55
60
  python_version = "3.9"
56
61
  strict = true
57
-
58
- # nrf52_upload is only temporary in this package
59
- [[tool.mypy.overrides]]
60
- module = "nitrokey.trussed._bootloader.nrf52_upload.*"
61
- ignore_errors = true
62
-
63
- # nrf52 has to use the untyped nrf52_upload module
64
- [[tool.mypy.overrides]]
65
- module = "nitrokey.trussed._bootloader.nrf52"
66
- disallow_untyped_calls = false
@@ -14,8 +14,6 @@ from contextlib import contextmanager
14
14
  from io import BytesIO
15
15
  from typing import Any, Callable, Iterator, List, Optional
16
16
 
17
- from spsdk.mboot.exceptions import McuBootConnectionError
18
-
19
17
  from nitrokey._helpers import Retries
20
18
  from nitrokey.nk3 import NK3, NK3Bootloader
21
19
  from nitrokey.trussed import TimeoutException, TrussedBase, Version
@@ -25,6 +23,9 @@ from nitrokey.trussed._bootloader import (
25
23
  Variant,
26
24
  validate_firmware_image,
27
25
  )
26
+ from nitrokey.trussed._bootloader.lpc55_upload.mboot.exceptions import (
27
+ McuBootConnectionError,
28
+ )
28
29
  from nitrokey.trussed.admin_app import BootMode
29
30
  from nitrokey.updates import Asset, Release
30
31
 
@@ -11,16 +11,14 @@ import re
11
11
  import sys
12
12
  from typing import Optional, TypeVar
13
13
 
14
- from spsdk.mboot.interfaces.usb import MbootUSBInterface
15
- from spsdk.mboot.mcuboot import McuBoot
16
- from spsdk.mboot.properties import PropertyTag
17
- from spsdk.sbfile.sb2.images import BootImageV21
18
- from spsdk.utils.interfaces.device.usb_device import UsbDevice
19
- from spsdk.utils.usbfilter import USBDeviceFilter
20
-
21
14
  from nitrokey.trussed import Uuid, Version
22
15
 
23
16
  from . import FirmwareMetadata, ProgressCallback, TrussedBootloader, Variant
17
+ from .lpc55_upload.mboot.interfaces.usb import MbootUSBInterface
18
+ from .lpc55_upload.mboot.mcuboot import McuBoot
19
+ from .lpc55_upload.mboot.properties import PropertyTag
20
+ from .lpc55_upload.sbfile.sb2.images import BootImageV21
21
+ from .lpc55_upload.utils.interfaces.device.usb_device import UsbDevice
24
22
 
25
23
  RKTH = bytes.fromhex("050aad3e77791a81e59c5b2ba5a158937e9460ee325d8ccba09734b8fdebb171")
26
24
  KEK = bytes([0xAA] * 32)
@@ -102,9 +100,8 @@ class TrussedBootloaderLpc55(TrussedBootloader):
102
100
 
103
101
  @classmethod
104
102
  def _list_vid_pid(cls: type[T], vid: int, pid: int) -> list[T]:
105
- device_filter = USBDeviceFilter(f"0x{vid:x}:0x{pid:x}")
106
103
  devices = []
107
- for device in UsbDevice.enumerate(device_filter):
104
+ for device in UsbDevice.enumerate(vid=vid, pid=pid):
108
105
  try:
109
106
  devices.append(cls(device))
110
107
  except ValueError:
@@ -115,8 +112,7 @@ class TrussedBootloaderLpc55(TrussedBootloader):
115
112
 
116
113
  @classmethod
117
114
  def _open(cls: type[T], path: str) -> Optional[T]:
118
- device_filter = USBDeviceFilter(path)
119
- devices = UsbDevice.enumerate(device_filter)
115
+ devices = UsbDevice.enumerate(path=path)
120
116
  if len(devices) == 0:
121
117
  logger.warn(f"No HID device at {path}")
122
118
  return None
@@ -135,7 +131,10 @@ class TrussedBootloaderLpc55(TrussedBootloader):
135
131
 
136
132
  def parse_firmware_image(data: bytes) -> FirmwareMetadata:
137
133
  image = BootImageV21.parse(data, kek=KEK)
138
- version = Version.from_bcd_version(image.header.product_version)
134
+ bcd_version = image.header.product_version
135
+ version = Version(
136
+ major=bcd_version.major, minor=bcd_version.minor, patch=bcd_version.service
137
+ )
139
138
  metadata = FirmwareMetadata(version=version)
140
139
  if image.cert_block:
141
140
  if image.cert_block.rkth == RKTH:
@@ -0,0 +1,6 @@
1
+ # LPC55 Bootloader Firmware Upload Module
2
+
3
+ Anything inside this directory is originally extracted from: https://github.com/nxp-mcuxpresso/spsdk/tree/master.
4
+ In detail anything that is needed to upload a signed firmware image to a Nitrokey 3 xN with an LPC55 MCU.
5
+
6
+
@@ -0,0 +1,13 @@
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
+ version = "2.1.0"
9
+
10
+ __author__ = "NXP"
11
+ __license__ = "BSD-3-Clause"
12
+ __version__ = version
13
+ __release__ = "beta"
@@ -0,0 +1,7 @@
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 crypto operations (certificate and key management)."""
@@ -0,0 +1,208 @@
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 certificate management (generating certificate, validating certificate, chains)."""
8
+
9
+ from typing import Optional
10
+
11
+ from cryptography import x509
12
+ from cryptography.hazmat.primitives import hashes
13
+ from cryptography.hazmat.primitives.asymmetric import rsa
14
+
15
+ from ..crypto.hash import EnumHashAlgorithm
16
+ from ..crypto.keys import PublicKey, PublicKeyRsa
17
+ from ..crypto.types import (
18
+ SPSDKEncoding,
19
+ SPSDKExtensionOID,
20
+ SPSDKExtensions,
21
+ SPSDKName,
22
+ SPSDKVersion,
23
+ )
24
+ from ..exceptions import SPSDKError, SPSDKValueError
25
+ from ..utils.abstract import BaseClass
26
+ from ..utils.misc import align_block
27
+
28
+
29
+ class Certificate(BaseClass):
30
+ """SPSDK Certificate representation."""
31
+
32
+ def __init__(self, certificate: x509.Certificate) -> None:
33
+ """Constructor of SPSDK Certificate.
34
+
35
+ :param certificate: Cryptography Certificate representation.
36
+ """
37
+ assert isinstance(certificate, x509.Certificate)
38
+ self.cert = certificate
39
+
40
+ def export(self, encoding: SPSDKEncoding = SPSDKEncoding.NXP) -> bytes:
41
+ """Convert certificates into bytes.
42
+
43
+ :param encoding: encoding type
44
+ :return: certificate in bytes form
45
+ """
46
+ if encoding == SPSDKEncoding.NXP:
47
+ return align_block(self.export(SPSDKEncoding.DER), 4, "zeros")
48
+
49
+ return self.cert.public_bytes(
50
+ SPSDKEncoding.get_cryptography_encodings(encoding)
51
+ )
52
+
53
+ def get_public_key(self) -> PublicKey:
54
+ """Get public keys from certificate.
55
+
56
+ :return: RSA public key
57
+ """
58
+ pub_key = self.cert.public_key()
59
+ if isinstance(pub_key, rsa.RSAPublicKey):
60
+ return PublicKeyRsa(pub_key)
61
+
62
+ raise SPSDKError(f"Unsupported Certificate public key: {type(pub_key)}")
63
+
64
+ @property
65
+ def version(self) -> SPSDKVersion:
66
+ """Returns the certificate version."""
67
+ return self.cert.version
68
+
69
+ @property
70
+ def signature(self) -> bytes:
71
+ """Returns the signature bytes."""
72
+ return self.cert.signature
73
+
74
+ @property
75
+ def tbs_certificate_bytes(self) -> bytes:
76
+ """Returns the tbsCertificate payload bytes as defined in RFC 5280."""
77
+ return self.cert.tbs_certificate_bytes
78
+
79
+ @property
80
+ def signature_hash_algorithm(
81
+ self,
82
+ ) -> Optional[hashes.HashAlgorithm]:
83
+ """Returns a HashAlgorithm corresponding to the type of the digest signed in the certificate."""
84
+ return self.cert.signature_hash_algorithm
85
+
86
+ @property
87
+ def extensions(self) -> SPSDKExtensions:
88
+ """Returns an Extensions object."""
89
+ return self.cert.extensions
90
+
91
+ @property
92
+ def issuer(self) -> SPSDKName:
93
+ """Returns the issuer name object."""
94
+ return self.cert.issuer
95
+
96
+ @property
97
+ def serial_number(self) -> int:
98
+ """Returns certificate serial number."""
99
+ return self.cert.serial_number
100
+
101
+ @property
102
+ def subject(self) -> SPSDKName:
103
+ """Returns the subject name object."""
104
+ return self.cert.subject
105
+
106
+ def validate(self, issuer_certificate: "Certificate") -> bool:
107
+ """Validate certificate.
108
+
109
+ :param issuer_certificate: Issuer's certificate
110
+ :raises SPSDKError: Unsupported key type in Certificate
111
+ :return: true/false whether certificate is valid or not
112
+ """
113
+ assert self.signature_hash_algorithm
114
+ return issuer_certificate.get_public_key().verify_signature(
115
+ self.signature,
116
+ self.tbs_certificate_bytes,
117
+ EnumHashAlgorithm.from_label(self.signature_hash_algorithm.name),
118
+ )
119
+
120
+ @property
121
+ def ca(self) -> bool:
122
+ """Check if CA flag is set in certificate.
123
+
124
+ :return: true/false depending whether ca flag is set or not
125
+ """
126
+ extension = self.extensions.get_extension_for_oid(
127
+ SPSDKExtensionOID.BASIC_CONSTRAINTS
128
+ )
129
+ return extension.value.ca # type: ignore # mypy can not handle property definition in cryptography
130
+
131
+ @property
132
+ def self_signed(self) -> bool:
133
+ """Indication whether the Certificate is self-signed."""
134
+ return self.validate(self)
135
+
136
+ @property
137
+ def raw_size(self) -> int:
138
+ """Raw size of the certificate."""
139
+ return len(self.export())
140
+
141
+ def public_key_hash(
142
+ self, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256
143
+ ) -> bytes:
144
+ """Get key hash.
145
+
146
+ :param algorithm: Used hash algorithm, defaults to sha256
147
+ :return: Key Hash
148
+ """
149
+ return self.get_public_key().key_hash(algorithm)
150
+
151
+ def __repr__(self) -> str:
152
+ """Text short representation about the Certificate."""
153
+ return f"Certificate, SN:{hex(self.cert.serial_number)}"
154
+
155
+ def __str__(self) -> str:
156
+ """Text information about the Certificate."""
157
+ not_valid_before = self.cert.not_valid_before.strftime("%d.%m.%Y (%H:%M:%S)")
158
+ not_valid_after = self.cert.not_valid_after.strftime("%d.%m.%Y (%H:%M:%S)")
159
+ nfo = ""
160
+ nfo += f" Certification Authority: {'YES' if self.ca else 'NO'}\n"
161
+ nfo += f" Serial Number: {hex(self.cert.serial_number)}\n"
162
+ nfo += f" Validity Range: {not_valid_before} - {not_valid_after}\n"
163
+ if self.signature_hash_algorithm:
164
+ nfo += (
165
+ f" Signature Algorithm: {self.signature_hash_algorithm.name}\n"
166
+ )
167
+ nfo += f" Self Issued: {'YES' if self.self_signed else 'NO'}\n"
168
+
169
+ return nfo
170
+
171
+ @classmethod
172
+ def parse(cls, data: bytes) -> "Certificate":
173
+ """Deserialize object from bytes array.
174
+
175
+ :param data: Data to be parsed
176
+ :returns: Recreated certificate
177
+ """
178
+
179
+ def load_der_certificate(data: bytes) -> x509.Certificate:
180
+ """Load the DER certificate from bytes.
181
+
182
+ This function is designed to eliminate cryptography exception
183
+ when the padded data is provided.
184
+
185
+ :param data: Data with DER certificate
186
+ :return: Certificate (from cryptography library)
187
+ :raises SPSDKError: Unsupported certificate to load
188
+ """
189
+ while True:
190
+ try:
191
+ return x509.load_der_x509_certificate(data)
192
+ except ValueError as exc:
193
+ if (
194
+ len(exc.args)
195
+ and "kind: ExtraData" in exc.args[0]
196
+ and data[-1:] == b"\00"
197
+ ):
198
+ data = data[:-1]
199
+ else:
200
+ raise SPSDKValueError(str(exc)) from exc
201
+
202
+ try:
203
+ encoding = SPSDKEncoding.get_file_encodings(data)
204
+ if encoding != SPSDKEncoding.DER:
205
+ raise ValueError("Unsupported encoding: {encoding}")
206
+ return Certificate(load_der_certificate(data))
207
+ except ValueError as exc:
208
+ raise SPSDKError(f"Cannot load certificate: ({str(exc)})") from exc
@@ -0,0 +1,107 @@
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(
40
+ hashes, algorithm.label.upper(), None
41
+ ) # hack: get class object by name
42
+ if algo_cls is None:
43
+ raise SPSDKError(f"Unsupported algorithm: hashes.{algorithm.label.upper()}")
44
+
45
+ algo = algo_cls()
46
+ assert isinstance(algo, hashes.HashAlgorithm)
47
+ return algo
48
+
49
+
50
+ def get_hash_length(algorithm: EnumHashAlgorithm) -> int:
51
+ """For specified name return hash binary length.
52
+
53
+ :param algorithm: Algorithm type enum
54
+ :return: Hash length
55
+ :raises SPSDKError: If algorithm not found
56
+ """
57
+ return get_hash_algorithm(algorithm).digest_size
58
+
59
+
60
+ class Hash:
61
+ """SPSDK Hash Class."""
62
+
63
+ def __init__(self, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256) -> None:
64
+ """Initialize hash object.
65
+
66
+ :param algorithm: Algorithm type enum, defaults to EnumHashAlgorithm.SHA256
67
+ """
68
+ self.hash_obj = hashes.Hash(get_hash_algorithm(algorithm))
69
+
70
+ def update(self, data: bytes) -> None:
71
+ """Update the hash by new data.
72
+
73
+ :param data: Data to be hashed
74
+ """
75
+ self.hash_obj.update(data)
76
+
77
+ def update_int(self, value: int) -> None:
78
+ """Update the hash by new integer value as is.
79
+
80
+ :param value: Integer value to be hashed
81
+ """
82
+ data = value.to_bytes(
83
+ length=ceil(value.bit_length() / 8), byteorder=Endianness.BIG.value
84
+ )
85
+ self.update(data)
86
+
87
+ def finalize(self) -> bytes:
88
+ """Finalize the hash and return the hash value.
89
+
90
+ :returns: Computed hash
91
+ """
92
+ return self.hash_obj.finalize()
93
+
94
+
95
+ def get_hash(
96
+ data: bytes, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256
97
+ ) -> bytes:
98
+ """Return a HASH from input data with specified algorithm.
99
+
100
+ :param data: Input data in bytes
101
+ :param algorithm: Algorithm type enum
102
+ :return: Hash-ed bytes
103
+ :raises SPSDKError: If algorithm not found
104
+ """
105
+ hash_obj = hashes.Hash(get_hash_algorithm(algorithm))
106
+ hash_obj.update(data)
107
+ return hash_obj.finalize()
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ #
4
+ # Copyright 2019-2023 NXP
5
+ #
6
+ # SPDX-License-Identifier: BSD-3-Clause
7
+
8
+ """OpenSSL implementation for HMAC packet authentication."""
9
+
10
+ # Used security modules
11
+ from cryptography.hazmat.primitives import hashes
12
+ from cryptography.hazmat.primitives import hmac as hmac_cls
13
+
14
+
15
+ def hmac_sha256(key: bytes, data: bytes) -> bytes:
16
+ """Return a HMAC from data with specified key and algorithm.
17
+
18
+ :param key: The key in bytes format
19
+ :param data: Input data in bytes format
20
+ :return: HMAC bytes
21
+ """
22
+ hmac_obj = hmac_cls.HMAC(key, hashes.SHA256())
23
+ hmac_obj.update(data)
24
+ return hmac_obj.finalize()