_mode_kwp.py 3.8 KB

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