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