keywrap.py 5.5 KB

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