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