keywrap.py 5.6 KB

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