_PBES.py 19 KB

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