_PBES.py 22 KB

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