keywrap.py 6.0 KB

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