keywrap.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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: 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: list[bytes],
  48. ) -> tuple[bytes, 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. if not key_to_wrap or len(key_to_wrap) > 2**32:
  72. raise ValueError("key_to_wrap must be between 1 and 2^32 bytes")
  73. aiv = b"\xa6\x59\x59\xa6" + len(key_to_wrap).to_bytes(
  74. length=4, byteorder="big"
  75. )
  76. # pad the key to wrap if necessary
  77. pad = (8 - (len(key_to_wrap) % 8)) % 8
  78. key_to_wrap = key_to_wrap + b"\x00" * pad
  79. if len(key_to_wrap) == 8:
  80. # RFC 5649 - 4.1 - exactly 8 octets after padding
  81. encryptor = Cipher(AES(wrapping_key), ECB()).encryptor()
  82. b = encryptor.update(aiv + key_to_wrap)
  83. assert encryptor.finalize() == b""
  84. return b
  85. else:
  86. r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)]
  87. return _wrap_core(wrapping_key, aiv, r)
  88. def aes_key_unwrap_with_padding(
  89. wrapping_key: bytes,
  90. wrapped_key: bytes,
  91. backend: typing.Any = None,
  92. ) -> bytes:
  93. if len(wrapped_key) < 16:
  94. raise InvalidUnwrap("Must be at least 16 bytes")
  95. if len(wrapping_key) not in [16, 24, 32]:
  96. raise ValueError("The wrapping key must be a valid AES key length")
  97. if len(wrapped_key) == 16:
  98. # RFC 5649 - 4.2 - exactly two 64-bit blocks
  99. decryptor = Cipher(AES(wrapping_key), ECB()).decryptor()
  100. out = decryptor.update(wrapped_key)
  101. assert decryptor.finalize() == b""
  102. a = out[:8]
  103. data = out[8:]
  104. n = 1
  105. else:
  106. r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)]
  107. encrypted_aiv = r.pop(0)
  108. n = len(r)
  109. a, r = _unwrap_core(wrapping_key, encrypted_aiv, r)
  110. data = b"".join(r)
  111. # 1) Check that MSB(32,A) = A65959A6.
  112. # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let
  113. # MLI = LSB(32,A).
  114. # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of
  115. # the output data are zero.
  116. mli = int.from_bytes(a[4:], byteorder="big")
  117. b = (8 * n) - mli
  118. if (
  119. not bytes_eq(a[:4], b"\xa6\x59\x59\xa6")
  120. or not 8 * (n - 1) < mli <= 8 * n
  121. or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b))
  122. ):
  123. raise InvalidUnwrap()
  124. if b == 0:
  125. return data
  126. else:
  127. return data[:-b]
  128. def aes_key_unwrap(
  129. wrapping_key: bytes,
  130. wrapped_key: bytes,
  131. backend: typing.Any = None,
  132. ) -> bytes:
  133. if len(wrapped_key) < 24:
  134. raise InvalidUnwrap("Must be at least 24 bytes")
  135. if len(wrapped_key) % 8 != 0:
  136. raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes")
  137. if len(wrapping_key) not in [16, 24, 32]:
  138. raise ValueError("The wrapping key must be a valid AES key length")
  139. aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
  140. r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)]
  141. a = r.pop(0)
  142. a, r = _unwrap_core(wrapping_key, a, r)
  143. if not bytes_eq(a, aiv):
  144. raise InvalidUnwrap()
  145. return b"".join(r)
  146. class InvalidUnwrap(Exception):
  147. pass