Debian Codegraph @

lib/Crypto/Cipher/_mode_openpgp.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 """
32 OpenPGP mode.
33 """
34
35 __all__ = ['OpenPgpMode']
36
37 from Crypto.Util.py3compat import _copy_bytes
38 from Crypto.Random import get_random_bytes
39
40 class OpenPgpMode(object):
41 """OpenPGP mode.
42
43 This mode is a variant of CFB, and it is only used in PGP and
44 OpenPGP_ applications. If in doubt, use another mode.
45
46 An Initialization Vector (*IV*) is required.
47
48 Unlike CFB, the *encrypted* IV (not the IV itself) is
49 transmitted to the receiver.
50
51 The IV is a random data block. For legacy reasons, two of its bytes are
52 duplicated to act as a checksum for the correctness of the key, which is now
53 known to be insecure and is ignored. The encrypted IV is therefore 2 bytes
54 longer than the clean IV.
55
56 .. _OpenPGP: http://tools.ietf.org/html/rfc4880
57
58 :undocumented: __init__
59 """
60
61 def __init__(self, factory, key, iv, cipher_params):
62
63 #: The block size of the underlying cipher, in bytes.
64 self.block_size = factory.block_size
65
66 self._done_first_block = False # True after the first encryption
67
68 # Instantiate a temporary cipher to process the IV
69 IV_cipher = factory.new(
70 key,
71 factory.MODE_CFB,
72 IV=b'\x00' * self.block_size,
73 segment_size=self.block_size * 8,
74 **cipher_params)
75
76 iv = _copy_bytes(None, None, iv)
77
78 # The cipher will be used for...
79 if len(iv) == self.block_size:
80 # ... encryption
81 self._encrypted_IV = IV_cipher.encrypt(iv + iv[-2:])
82 elif len(iv) == self.block_size + 2:
83 # ... decryption
84 self._encrypted_IV = iv
85 # Last two bytes are for a deprecated "quick check" feature that
86 # should not be used. (https://eprint.iacr.org/2005/033)
87 iv = IV_cipher.decrypt(iv)[:-2]
88 else:
89 raise ValueError("Length of IV must be %d or %d bytes"
90 " for MODE_OPENPGP"
91 % (self.block_size, self.block_size + 2))
92
93 self.iv = self.IV = iv
94
95 # Instantiate the cipher for the real PGP data
96 self._cipher = factory.new(
97 key,
98 factory.MODE_CFB,
99 IV=self._encrypted_IV[-self.block_size:],
100 segment_size=self.block_size * 8,
101 **cipher_params)
102
103 def encrypt(self, plaintext):
104 """Encrypt data with the key and the parameters set at initialization.
105
106 A cipher object is stateful: once you have encrypted a message
107 you cannot encrypt (or decrypt) another message using the same
108 object.
109
110 The data to encrypt can be broken up in two or
111 more pieces and `encrypt` can be called multiple times.
112
113 That is, the statement:
114
115 >>> c.encrypt(a) + c.encrypt(b)
116
117 is equivalent to:
118
119 >>> c.encrypt(a+b)
120
121 This function does not add any padding to the plaintext.
122
123 :Parameters:
124 plaintext : bytes/bytearray/memoryview
125 The piece of data to encrypt.
126
127 :Return:
128 the encrypted data, as a byte string.
129 It is as long as *plaintext* with one exception:
130 when encrypting the first message chunk,
131 the encypted IV is prepended to the returned ciphertext.
132 """
133
134 res = self._cipher.encrypt(plaintext)
135 if not self._done_first_block:
136 res = self._encrypted_IV + res
137 self._done_first_block = True
138 return res
139
140 def decrypt(self, ciphertext):
141 """Decrypt data with the key and the parameters set at initialization.
142
143 A cipher object is stateful: once you have decrypted a message
144 you cannot decrypt (or encrypt) another message with the same
145 object.
146
147 The data to decrypt can be broken up in two or
148 more pieces and `decrypt` can be called multiple times.
149
150 That is, the statement:
151
152 >>> c.decrypt(a) + c.decrypt(b)
153
154 is equivalent to:
155
156 >>> c.decrypt(a+b)
157
158 This function does not remove any padding from the plaintext.
159
160 :Parameters:
161 ciphertext : bytes/bytearray/memoryview
162 The piece of data to decrypt.
163
164 :Return: the decrypted data (byte string).
165 """
166
167 return self._cipher.decrypt(ciphertext)
168
169
170 def _create_openpgp_cipher(factory, **kwargs):
171 """Create a new block cipher, configured in OpenPGP mode.
172
173 :Parameters:
174 factory : module
175 The module.
176
177 :Keywords:
178 key : bytes/bytearray/memoryview
179 The secret key to use in the symmetric cipher.
180
181 IV : bytes/bytearray/memoryview
182 The initialization vector to use for encryption or decryption.
183
184 For encryption, the IV must be as long as the cipher block size.
185
186 For decryption, it must be 2 bytes longer (it is actually the
187 *encrypted* IV which was prefixed to the ciphertext).
188 """
189
190 iv = kwargs.pop("IV", None)
191 IV = kwargs.pop("iv", None)
192
193 if (None, None) == (iv, IV):
194 iv = get_random_bytes(factory.block_size)
195 if iv is not None:
196 if IV is not None:
197 raise TypeError("You must either use 'iv' or 'IV', not both")
198 else:
199 iv = IV
200
201 try:
202 key = kwargs.pop("key")
203 except KeyError as e:
204 raise TypeError("Missing component: " + str(e))
205
206 return OpenPgpMode(factory, key, iv, kwargs)