keywrap.py 5.8 KB

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