Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

keywrap.py 5.5KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import annotations
  5. import typing
  6. from cryptography.hazmat.primitives.ciphers import Cipher
  7. from cryptography.hazmat.primitives.ciphers.algorithms import AES
  8. from cryptography.hazmat.primitives.ciphers.modes import ECB
  9. from cryptography.hazmat.primitives.constant_time import bytes_eq
  10. def _wrap_core(
  11. wrapping_key: bytes,
  12. a: bytes,
  13. r: typing.List[bytes],
  14. ) -> bytes:
  15. # RFC 3394 Key Wrap - 2.2.1 (index method)
  16. encryptor = Cipher(AES(wrapping_key), ECB()).encryptor()
  17. n = len(r)
  18. for j in range(6):
  19. for i in range(n):
  20. # every encryption operation is a discrete 16 byte chunk (because
  21. # AES has a 128-bit block size) and since we're using ECB it is
  22. # safe to reuse the encryptor for the entire operation
  23. b = encryptor.update(a + r[i])
  24. a = (
  25. int.from_bytes(b[:8], byteorder="big") ^ ((n * j) + i + 1)
  26. ).to_bytes(length=8, byteorder="big")
  27. r[i] = b[-8:]
  28. assert encryptor.finalize() == b""
  29. return a + b"".join(r)
  30. def aes_key_wrap(
  31. wrapping_key: bytes,
  32. key_to_wrap: bytes,
  33. backend: typing.Any = None,
  34. ) -> bytes:
  35. if len(wrapping_key) not in [16, 24, 32]:
  36. raise ValueError("The wrapping key must be a valid AES key length")
  37. if len(key_to_wrap) < 16:
  38. raise ValueError("The key to wrap must be at least 16 bytes")
  39. if len(key_to_wrap) % 8 != 0:
  40. raise ValueError("The key to wrap must be a multiple of 8 bytes")
  41. a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
  42. r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)]
  43. return _wrap_core(wrapping_key, a, r)
  44. def _unwrap_core(
  45. wrapping_key: bytes,
  46. a: bytes,
  47. r: typing.List[bytes],
  48. ) -> typing.Tuple[bytes, typing.List[bytes]]:
  49. # Implement RFC 3394 Key Unwrap - 2.2.2 (index method)
  50. decryptor = Cipher(AES(wrapping_key), ECB()).decryptor()
  51. n = len(r)
  52. for j in reversed(range(6)):
  53. for i in reversed(range(n)):
  54. atr = (
  55. int.from_bytes(a, byteorder="big") ^ ((n * j) + i + 1)
  56. ).to_bytes(length=8, byteorder="big") + r[i]
  57. # every decryption operation is a discrete 16 byte chunk so
  58. # it is safe to reuse the decryptor for the entire operation
  59. b = decryptor.update(atr)
  60. a = b[:8]
  61. r[i] = b[-8:]
  62. assert decryptor.finalize() == b""
  63. return a, r
  64. def aes_key_wrap_with_padding(
  65. wrapping_key: bytes,
  66. key_to_wrap: bytes,
  67. backend: typing.Any = None,
  68. ) -> bytes:
  69. if len(wrapping_key) not in [16, 24, 32]:
  70. raise ValueError("The wrapping key must be a valid AES key length")
  71. aiv = b"\xA6\x59\x59\xA6" + len(key_to_wrap).to_bytes(
  72. length=4, byteorder="big"
  73. )
  74. # pad the key to wrap if necessary
  75. pad = (8 - (len(key_to_wrap) % 8)) % 8
  76. key_to_wrap = key_to_wrap + b"\x00" * pad
  77. if len(key_to_wrap) == 8:
  78. # RFC 5649 - 4.1 - exactly 8 octets after padding
  79. encryptor = Cipher(AES(wrapping_key), ECB()).encryptor()
  80. b = encryptor.update(aiv + key_to_wrap)
  81. assert encryptor.finalize() == b""
  82. return b
  83. else:
  84. r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)]
  85. return _wrap_core(wrapping_key, aiv, r)
  86. def aes_key_unwrap_with_padding(
  87. wrapping_key: bytes,
  88. wrapped_key: bytes,
  89. backend: typing.Any = None,
  90. ) -> bytes:
  91. if len(wrapped_key) < 16:
  92. raise InvalidUnwrap("Must be at least 16 bytes")
  93. if len(wrapping_key) not in [16, 24, 32]:
  94. raise ValueError("The wrapping key must be a valid AES key length")
  95. if len(wrapped_key) == 16:
  96. # RFC 5649 - 4.2 - exactly two 64-bit blocks
  97. decryptor = Cipher(AES(wrapping_key), ECB()).decryptor()
  98. out = decryptor.update(wrapped_key)
  99. assert decryptor.finalize() == b""
  100. a = out[:8]
  101. data = out[8:]
  102. n = 1
  103. else:
  104. r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)]
  105. encrypted_aiv = r.pop(0)
  106. n = len(r)
  107. a, r = _unwrap_core(wrapping_key, encrypted_aiv, r)
  108. data = b"".join(r)
  109. # 1) Check that MSB(32,A) = A65959A6.
  110. # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let
  111. # MLI = LSB(32,A).
  112. # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of
  113. # the output data are zero.
  114. mli = int.from_bytes(a[4:], byteorder="big")
  115. b = (8 * n) - mli
  116. if (
  117. not bytes_eq(a[:4], b"\xa6\x59\x59\xa6")
  118. or not 8 * (n - 1) < mli <= 8 * n
  119. or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b))
  120. ):
  121. raise InvalidUnwrap()
  122. if b == 0:
  123. return data
  124. else:
  125. return data[:-b]
  126. def aes_key_unwrap(
  127. wrapping_key: bytes,
  128. wrapped_key: bytes,
  129. backend: typing.Any = None,
  130. ) -> bytes:
  131. if len(wrapped_key) < 24:
  132. raise InvalidUnwrap("Must be at least 24 bytes")
  133. if len(wrapped_key) % 8 != 0:
  134. raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes")
  135. if len(wrapping_key) not in [16, 24, 32]:
  136. raise ValueError("The wrapping key must be a valid AES key length")
  137. aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
  138. r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)]
  139. a = r.pop(0)
  140. a, r = _unwrap_core(wrapping_key, a, r)
  141. if not bytes_eq(a, aiv):
  142. raise InvalidUnwrap()
  143. return b"".join(r)
  144. class InvalidUnwrap(Exception):
  145. pass