Debian Codegraph @

lib/Crypto/IO/_PBES.py

raw symbols SCIP
1 #
2 # PublicKey/_PBES.py : Password-Based Encryption functions
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 import re
35
36 from Crypto import Hash
37 from Crypto import Random
38 from Crypto.Util.asn1 import (
39 DerSequence, DerOctetString,
40 DerObjectId, DerInteger,
41 )
42
43 from Crypto.Cipher import AES
44 from Crypto.Util.Padding import pad, unpad
45 from Crypto.Protocol.KDF import PBKDF1, PBKDF2, scrypt
46
47 _OID_PBE_WITH_MD5_AND_DES_CBC = "1.2.840.113549.1.5.3"
48 _OID_PBE_WITH_MD5_AND_RC2_CBC = "1.2.840.113549.1.5.6"
49 _OID_PBE_WITH_SHA1_AND_DES_CBC = "1.2.840.113549.1.5.10"
50 _OID_PBE_WITH_SHA1_AND_RC2_CBC = "1.2.840.113549.1.5.11"
51
52 _OID_PBES2 = "1.2.840.113549.1.5.13"
53
54 _OID_PBKDF2 = "1.2.840.113549.1.5.12"
55 _OID_SCRYPT = "1.3.6.1.4.1.11591.4.11"
56
57 _OID_HMAC_SHA1 = "1.2.840.113549.2.7"
58
59 _OID_DES_EDE3_CBC = "1.2.840.113549.3.7"
60 _OID_AES128_CBC = "2.16.840.1.101.3.4.1.2"
61 _OID_AES192_CBC = "2.16.840.1.101.3.4.1.22"
62 _OID_AES256_CBC = "2.16.840.1.101.3.4.1.42"
63 _OID_AES128_GCM = "2.16.840.1.101.3.4.1.6"
64 _OID_AES192_GCM = "2.16.840.1.101.3.4.1.26"
65 _OID_AES256_GCM = "2.16.840.1.101.3.4.1.46"
66
67 class PbesError(ValueError):
68 pass
69
70 # These are the ASN.1 definitions used by the PBES1/2 logic:
71 #
72 # EncryptedPrivateKeyInfo ::= SEQUENCE {
73 # encryptionAlgorithm EncryptionAlgorithmIdentifier,
74 # encryptedData EncryptedData
75 # }
76 #
77 # EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
78 #
79 # EncryptedData ::= OCTET STRING
80 #
81 # AlgorithmIdentifier ::= SEQUENCE {
82 # algorithm OBJECT IDENTIFIER,
83 # parameters ANY DEFINED BY algorithm OPTIONAL
84 # }
85 #
86 # PBEParameter ::= SEQUENCE {
87 # salt OCTET STRING (SIZE(8)),
88 # iterationCount INTEGER
89 # }
90 #
91 # PBES2-params ::= SEQUENCE {
92 # keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
93 # encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
94 # }
95 #
96 # PBKDF2-params ::= SEQUENCE {
97 # salt CHOICE {
98 # specified OCTET STRING,
99 # otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
100 # },
101 # iterationCount INTEGER (1..MAX),
102 # keyLength INTEGER (1..MAX) OPTIONAL,
103 # prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
104 # }
105 #
106 # PBKDF2-PRFs ALGORITHM-IDENTIFIER ::= {
107 # {NULL IDENTIFIED BY id-hmacWithSHA1},
108 # {NULL IDENTIFIED BY id-hmacWithSHA224},
109 # {NULL IDENTIFIED BY id-hmacWithSHA256},
110 # {NULL IDENTIFIED BY id-hmacWithSHA384},
111 # {NULL IDENTIFIED BY id-hmacWithSHA512},
112 # {NULL IDENTIFIED BY id-hmacWithSHA512-224},
113 # {NULL IDENTIFIED BY id-hmacWithSHA512-256},
114 # ...
115 # }
116 # scrypt-params ::= SEQUENCE {
117 # salt OCTET STRING,
118 # costParameter INTEGER (1..MAX),
119 # blockSize INTEGER (1..MAX),
120 # parallelizationParameter INTEGER (1..MAX),
121 # keyLength INTEGER (1..MAX) OPTIONAL
122 # }
123
124
125 class PBES1(object):
126 """Deprecated encryption scheme with password-based key derivation
127 (originally defined in PKCS#5 v1.5, but still present in `v2.0`__).
128
129 .. __: http://www.ietf.org/rfc/rfc2898.txt
130 """
131
132 @staticmethod
133 def decrypt(data, passphrase):
134 """Decrypt a piece of data using a passphrase and *PBES1*.
135
136 The algorithm to use is automatically detected.
137
138 :Parameters:
139 data : byte string
140 The piece of data to decrypt.
141 passphrase : byte string
142 The passphrase to use for decrypting the data.
143 :Returns:
144 The decrypted data, as a binary string.
145 """
146
147 enc_private_key_info = DerSequence().decode(data)
148 encrypted_algorithm = DerSequence().decode(enc_private_key_info[0])
149 encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
150
151 pbe_oid = DerObjectId().decode(encrypted_algorithm[0]).value
152 cipher_params = {}
153 if pbe_oid == _OID_PBE_WITH_MD5_AND_DES_CBC:
154 # PBE_MD5_DES_CBC
155 from Crypto.Hash import MD5
156 from Crypto.Cipher import DES
157 hashmod = MD5
158 module = DES
159 elif pbe_oid == _OID_PBE_WITH_MD5_AND_RC2_CBC:
160 # PBE_MD5_RC2_CBC
161 from Crypto.Hash import MD5
162 from Crypto.Cipher import ARC2
163 hashmod = MD5
164 module = ARC2
165 cipher_params['effective_keylen'] = 64
166 elif pbe_oid == _OID_PBE_WITH_SHA1_AND_DES_CBC:
167 # PBE_SHA1_DES_CBC
168 from Crypto.Hash import SHA1
169 from Crypto.Cipher import DES
170 hashmod = SHA1
171 module = DES
172 elif pbe_oid == _OID_PBE_WITH_SHA1_AND_RC2_CBC:
173 # PBE_SHA1_RC2_CBC
174 from Crypto.Hash import SHA1
175 from Crypto.Cipher import ARC2
176 hashmod = SHA1
177 module = ARC2
178 cipher_params['effective_keylen'] = 64
179 else:
180 raise PbesError("Unknown OID for PBES1")
181
182 pbe_params = DerSequence().decode(encrypted_algorithm[1], nr_elements=2)
183 salt = DerOctetString().decode(pbe_params[0]).payload
184 iterations = pbe_params[1]
185
186 key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod)
187 key, iv = key_iv[:8], key_iv[8:]
188
189 cipher = module.new(key, module.MODE_CBC, iv, **cipher_params)
190 pt = cipher.decrypt(encrypted_data)
191 return unpad(pt, cipher.block_size)
192
193
194 class PBES2(object):
195 """Encryption scheme with password-based key derivation
196 (defined in `PKCS#5 v2.0`__).
197
198 .. __: http://www.ietf.org/rfc/rfc2898.txt."""
199
200 @staticmethod
201 def encrypt(data, passphrase, protection, prot_params=None, randfunc=None):
202 """Encrypt a piece of data using a passphrase and *PBES2*.
203
204 :Parameters:
205 data : byte string
206 The piece of data to encrypt.
207 passphrase : byte string
208 The passphrase to use for encrypting the data.
209 protection : string
210 The identifier of the encryption algorithm to use.
211 The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
212 prot_params : dictionary
213 Parameters of the protection algorithm.
214
215 +------------------+-----------------------------------------------+
216 | Key | Description |
217 +==================+===============================================+
218 | iteration_count | The KDF algorithm is repeated several times to|
219 | | slow down brute force attacks on passwords |
220 | | (called *N* or CPU/memory cost in scrypt). |
221 | | |
222 | | The default value for PBKDF2 is 1 000. |
223 | | The default value for scrypt is 16 384. |
224 +------------------+-----------------------------------------------+
225 | salt_size | Salt is used to thwart dictionary and rainbow |
226 | | attacks on passwords. The default value is 8 |
227 | | bytes. |
228 +------------------+-----------------------------------------------+
229 | block_size | *(scrypt only)* Memory-cost (r). The default |
230 | | value is 8. |
231 +------------------+-----------------------------------------------+
232 | parallelization | *(scrypt only)* CPU-cost (p). The default |
233 | | value is 1. |
234 +------------------+-----------------------------------------------+
235
236
237 randfunc : callable
238 Random number generation function; it should accept
239 a single integer N and return a string of random data,
240 N bytes long. If not specified, a new RNG will be
241 instantiated from ``Crypto.Random``.
242
243 :Returns:
244 The encrypted data, as a binary string.
245 """
246
247 if prot_params is None:
248 prot_params = {}
249
250 if randfunc is None:
251 randfunc = Random.new().read
252
253 pattern = re.compile(r'^(PBKDF2WithHMAC-([0-9A-Z-]+)|scrypt)And([0-9A-Z-]+)$')
254 res = pattern.match(protection)
255 if res is None:
256 raise ValueError("Unknown protection %s" % protection)
257
258 if protection.startswith("PBKDF"):
259 pbkdf = "pbkdf2"
260 pbkdf2_hmac_algo = res.group(2)
261 enc_algo = res.group(3)
262 else:
263 pbkdf = "scrypt"
264 enc_algo = res.group(3)
265
266 aead = False
267 if enc_algo == 'DES-EDE3-CBC':
268 from Crypto.Cipher import DES3
269 key_size = 24
270 module = DES3
271 cipher_mode = DES3.MODE_CBC
272 enc_oid = _OID_DES_EDE3_CBC
273 enc_param = {'iv': randfunc(8)}
274 elif enc_algo == 'AES128-CBC':
275 key_size = 16
276 module = AES
277 cipher_mode = AES.MODE_CBC
278 enc_oid = _OID_AES128_CBC
279 enc_param = {'iv': randfunc(16)}
280 elif enc_algo == 'AES192-CBC':
281 key_size = 24
282 module = AES
283 cipher_mode = AES.MODE_CBC
284 enc_oid = _OID_AES192_CBC
285 enc_param = {'iv': randfunc(16)}
286 elif enc_algo == 'AES256-CBC':
287 key_size = 32
288 module = AES
289 cipher_mode = AES.MODE_CBC
290 enc_oid = _OID_AES256_CBC
291 enc_param = {'iv': randfunc(16)}
292 elif enc_algo == 'AES128-GCM':
293 key_size = 16
294 module = AES
295 cipher_mode = AES.MODE_GCM
296 enc_oid = _OID_AES128_GCM
297 enc_param = {'nonce': randfunc(12)}
298 aead = True
299 elif enc_algo == 'AES192-GCM':
300 key_size = 24
301 module = AES
302 cipher_mode = AES.MODE_GCM
303 enc_oid = _OID_AES192_GCM
304 enc_param = {'nonce': randfunc(12)}
305 aead = True
306 elif enc_algo == 'AES256-GCM':
307 key_size = 32
308 module = AES
309 cipher_mode = AES.MODE_GCM
310 enc_oid = _OID_AES256_GCM
311 enc_param = {'nonce': randfunc(12)}
312 aead = True
313 else:
314 raise ValueError("Unknown encryption mode '%s'" % enc_algo)
315
316 iv_nonce = list(enc_param.values())[0]
317 salt = randfunc(prot_params.get("salt_size", 8))
318
319 # Derive key from password
320 if pbkdf == 'pbkdf2':
321
322 count = prot_params.get("iteration_count", 1000)
323 digestmod = Hash.new(pbkdf2_hmac_algo)
324
325 key = PBKDF2(passphrase,
326 salt,
327 key_size,
328 count,
329 hmac_hash_module=digestmod)
330
331 pbkdf2_params = DerSequence([
332 DerOctetString(salt),
333 DerInteger(count)
334 ])
335
336 if pbkdf2_hmac_algo != 'SHA1':
337 try:
338 hmac_oid = Hash.HMAC.new(b'', digestmod=digestmod).oid
339 except KeyError:
340 raise ValueError("No OID for HMAC hash algorithm")
341 pbkdf2_params.append(DerSequence([DerObjectId(hmac_oid)]))
342
343 kdf_info = DerSequence([
344 DerObjectId(_OID_PBKDF2), # PBKDF2
345 pbkdf2_params
346 ])
347
348 elif pbkdf == 'scrypt':
349
350 count = prot_params.get("iteration_count", 16384)
351 scrypt_r = prot_params.get('block_size', 8)
352 scrypt_p = prot_params.get('parallelization', 1)
353 key = scrypt(passphrase, salt, key_size,
354 count, scrypt_r, scrypt_p)
355 kdf_info = DerSequence([
356 DerObjectId(_OID_SCRYPT), # scrypt
357 DerSequence([
358 DerOctetString(salt),
359 DerInteger(count),
360 DerInteger(scrypt_r),
361 DerInteger(scrypt_p)
362 ])
363 ])
364
365 else:
366 raise ValueError("Unknown KDF " + res.group(1))
367
368 # Create cipher and use it
369 cipher = module.new(key, cipher_mode, **enc_param)
370 if aead:
371 ct, tag = cipher.encrypt_and_digest(data)
372 encrypted_data = ct + tag
373 else:
374 encrypted_data = cipher.encrypt(pad(data, cipher.block_size))
375 enc_info = DerSequence([
376 DerObjectId(enc_oid),
377 DerOctetString(iv_nonce)
378 ])
379
380 # Result
381 enc_private_key_info = DerSequence([
382 # encryptionAlgorithm
383 DerSequence([
384 DerObjectId(_OID_PBES2),
385 DerSequence([
386 kdf_info,
387 enc_info
388 ]),
389 ]),
390 DerOctetString(encrypted_data)
391 ])
392 return enc_private_key_info.encode()
393
394 @staticmethod
395 def decrypt(data, passphrase):
396 """Decrypt a piece of data using a passphrase and *PBES2*.
397
398 The algorithm to use is automatically detected.
399
400 :Parameters:
401 data : byte string
402 The piece of data to decrypt.
403 passphrase : byte string
404 The passphrase to use for decrypting the data.
405 :Returns:
406 The decrypted data, as a binary string.
407 """
408
409 enc_private_key_info = DerSequence().decode(data, nr_elements=2)
410 enc_algo = DerSequence().decode(enc_private_key_info[0])
411 encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
412
413 pbe_oid = DerObjectId().decode(enc_algo[0]).value
414 if pbe_oid != _OID_PBES2:
415 raise PbesError("Not a PBES2 object")
416
417 pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2)
418
419 # Key Derivation Function selection
420 kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2)
421 kdf_oid = DerObjectId().decode(kdf_info[0]).value
422
423 kdf_key_length = None
424
425 # We only support PBKDF2 or scrypt
426 if kdf_oid == _OID_PBKDF2:
427
428 pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4))
429 salt = DerOctetString().decode(pbkdf2_params[0]).payload
430 iteration_count = pbkdf2_params[1]
431
432 left = len(pbkdf2_params) - 2
433 idx = 2
434
435 if left > 0:
436 try:
437 # Check if it's an INTEGER
438 kdf_key_length = pbkdf2_params[idx] - 0
439 left -= 1
440 idx += 1
441 except TypeError:
442 # keyLength is not present
443 pass
444
445 # Default is HMAC-SHA1
446 pbkdf2_prf_oid = _OID_HMAC_SHA1
447 if left > 0:
448 pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx])
449 pbkdf2_prf_oid = DerObjectId().decode(pbkdf2_prf_algo_id[0]).value
450
451 elif kdf_oid == _OID_SCRYPT:
452
453 scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5))
454 salt = DerOctetString().decode(scrypt_params[0]).payload
455 iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
456 for x in (1, 2, 3)]
457 if len(scrypt_params) > 4:
458 kdf_key_length = scrypt_params[4]
459 else:
460 kdf_key_length = None
461 else:
462 raise PbesError("Unsupported PBES2 KDF")
463
464 # Cipher selection
465 enc_info = DerSequence().decode(pbes2_params[1])
466 enc_oid = DerObjectId().decode(enc_info[0]).value
467
468 aead = False
469 if enc_oid == _OID_DES_EDE3_CBC:
470 # DES_EDE3_CBC
471 from Crypto.Cipher import DES3
472 module = DES3
473 cipher_mode = DES3.MODE_CBC
474 key_size = 24
475 cipher_param = 'iv'
476 elif enc_oid == _OID_AES128_CBC:
477 module = AES
478 cipher_mode = AES.MODE_CBC
479 key_size = 16
480 cipher_param = 'iv'
481 elif enc_oid == _OID_AES192_CBC:
482 module = AES
483 cipher_mode = AES.MODE_CBC
484 key_size = 24
485 cipher_param = 'iv'
486 elif enc_oid == _OID_AES256_CBC:
487 module = AES
488 cipher_mode = AES.MODE_CBC
489 key_size = 32
490 cipher_param = 'iv'
491 elif enc_oid == _OID_AES128_GCM:
492 module = AES
493 cipher_mode = AES.MODE_GCM
494 key_size = 16
495 cipher_param = 'nonce'
496 aead = True
497 elif enc_oid == _OID_AES192_GCM:
498 module = AES
499 cipher_mode = AES.MODE_GCM
500 key_size = 24
501 cipher_param = 'nonce'
502 aead = True
503 elif enc_oid == _OID_AES256_GCM:
504 module = AES
505 cipher_mode = AES.MODE_GCM
506 key_size = 32
507 cipher_param = 'nonce'
508 aead = True
509 else:
510 raise PbesError("Unsupported PBES2 cipher " + enc_algo)
511
512 if kdf_key_length and kdf_key_length != key_size:
513 raise PbesError("Mismatch between PBES2 KDF parameters"
514 " and selected cipher")
515
516 iv_nonce = DerOctetString().decode(enc_info[1]).payload
517
518 # Create cipher
519 if kdf_oid == _OID_PBKDF2:
520
521 try:
522 hmac_hash_module_oid = Hash.HMAC._hmac2hash_oid[pbkdf2_prf_oid]
523 except KeyError:
524 raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid)
525 hmac_hash_module = Hash.new(hmac_hash_module_oid)
526
527 key = PBKDF2(passphrase, salt, key_size, iteration_count,
528 hmac_hash_module=hmac_hash_module)
529 else:
530 key = scrypt(passphrase, salt, key_size, iteration_count,
531 scrypt_r, scrypt_p)
532 cipher = module.new(key, cipher_mode, **{cipher_param:iv_nonce})
533
534 # Decrypt data
535 if len(encrypted_data) < cipher.block_size:
536 raise ValueError("Too little data to decrypt")
537
538 if aead:
539 tag_len = cipher.block_size
540 pt = cipher.decrypt_and_verify(encrypted_data[:-tag_len],
541 encrypted_data[-tag_len:])
542 else:
543 pt_padded = cipher.decrypt(encrypted_data)
544 pt = unpad(pt_padded, cipher.block_size)
545
546 return pt