_mode_kw.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import struct
  2. from collections import deque
  3. from types import ModuleType
  4. from typing import Union
  5. from Crypto.Util.strxor import strxor
  6. def W(cipher: ModuleType,
  7. plaintext: Union[bytes, bytearray]) -> bytes:
  8. S = [plaintext[i:i+8] for i in range(0, len(plaintext), 8)]
  9. n = len(S)
  10. s = 6 * (n - 1)
  11. A = S[0]
  12. R = deque(S[1:])
  13. for t in range(1, s + 1):
  14. t_64 = struct.pack('>Q', t)
  15. ct = cipher.encrypt(A + R.popleft())
  16. A = strxor(ct[:8], t_64)
  17. R.append(ct[8:])
  18. return A + b''.join(R)
  19. def W_inverse(cipher: ModuleType,
  20. ciphertext: Union[bytes, bytearray]) -> bytes:
  21. C = [ciphertext[i:i+8] for i in range(0, len(ciphertext), 8)]
  22. n = len(C)
  23. s = 6 * (n - 1)
  24. A = C[0]
  25. R = deque(C[1:])
  26. for t in range(s, 0, -1):
  27. t_64 = struct.pack('>Q', t)
  28. pt = cipher.decrypt(strxor(A, t_64) + R.pop())
  29. A = pt[:8]
  30. R.appendleft(pt[8:])
  31. return A + b''.join(R)
  32. class KWMode(object):
  33. """Key Wrap (KW) mode.
  34. This is a deterministic Authenticated Encryption (AE) mode
  35. for protecting cryptographic keys. See `NIST SP800-38F`_.
  36. It provides both confidentiality and authenticity, and it designed
  37. so that any bit of the ciphertext depends on all bits of the plaintext.
  38. This mode is only available for ciphers that operate on 128 bits blocks
  39. (e.g., AES).
  40. .. _`NIST SP800-38F`: http://csrc.nist.gov/publications/nistpubs/800-38F/SP-800-38F.pdf
  41. :undocumented: __init__
  42. """
  43. def __init__(self,
  44. factory: ModuleType,
  45. key: Union[bytes, bytearray]):
  46. self.block_size = factory.block_size
  47. if self.block_size != 16:
  48. raise ValueError("Key Wrap mode is only available for ciphers"
  49. " that operate on 128 bits blocks")
  50. self._factory = factory
  51. self._cipher = factory.new(key, factory.MODE_ECB)
  52. self._done = False
  53. def seal(self, plaintext: Union[bytes, bytearray]) -> bytes:
  54. """Encrypt and authenticate (wrap) a cryptographic key.
  55. Args:
  56. plaintext:
  57. The cryptographic key to wrap.
  58. It must be at least 16 bytes long, and its length
  59. must be a multiple of 8.
  60. Returns:
  61. The wrapped key.
  62. """
  63. if self._done:
  64. raise ValueError("The cipher cannot be used more than once")
  65. if len(plaintext) % 8:
  66. raise ValueError("The plaintext must have length multiple of 8 bytes")
  67. if len(plaintext) < 16:
  68. raise ValueError("The plaintext must be at least 16 bytes long")
  69. if len(plaintext) >= 2**32:
  70. raise ValueError("The plaintext is too long")
  71. res = W(self._cipher, b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6' + plaintext)
  72. self._done = True
  73. return res
  74. def unseal(self, ciphertext: Union[bytes, bytearray]) -> bytes:
  75. """Decrypt and authenticate (unwrap) a cryptographic key.
  76. Args:
  77. ciphertext:
  78. The cryptographic key to unwrap.
  79. It must be at least 24 bytes long, and its length
  80. must be a multiple of 8.
  81. Returns:
  82. The original key.
  83. Raises: ValueError
  84. If the ciphertext or the key are not valid.
  85. """
  86. if self._done:
  87. raise ValueError("The cipher cannot be used more than once")
  88. if len(ciphertext) % 8:
  89. raise ValueError("The ciphertext must have length multiple of 8 bytes")
  90. if len(ciphertext) < 24:
  91. raise ValueError("The ciphertext must be at least 24 bytes long")
  92. pt = W_inverse(self._cipher, ciphertext)
  93. if pt[:8] != b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6':
  94. raise ValueError("Incorrect integrity check value")
  95. self._done = True
  96. return pt[8:]
  97. def _create_kw_cipher(factory: ModuleType,
  98. **kwargs: Union[bytes, bytearray]) -> KWMode:
  99. """Create a new block cipher in Key Wrap mode.
  100. Args:
  101. factory:
  102. A block cipher module, taken from `Crypto.Cipher`.
  103. The cipher must have block length of 16 bytes, such as AES.
  104. Keywords:
  105. key:
  106. The secret key to use to seal or unseal.
  107. """
  108. try:
  109. key = kwargs["key"]
  110. except KeyError as e:
  111. raise TypeError("Missing parameter:" + str(e))
  112. return KWMode(factory, key)