hashers.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import base64
  2. import binascii
  3. import functools
  4. import hashlib
  5. import importlib
  6. import math
  7. import warnings
  8. from django.conf import settings
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.core.signals import setting_changed
  11. from django.dispatch import receiver
  12. from django.utils.crypto import (
  13. RANDOM_STRING_CHARS, constant_time_compare, get_random_string, pbkdf2,
  14. )
  15. from django.utils.module_loading import import_string
  16. from django.utils.translation import gettext_noop as _
  17. UNUSABLE_PASSWORD_PREFIX = '!' # This will never be a valid encoded hash
  18. UNUSABLE_PASSWORD_SUFFIX_LENGTH = 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX
  19. def is_password_usable(encoded):
  20. """
  21. Return True if this password wasn't generated by
  22. User.set_unusable_password(), i.e. make_password(None).
  23. """
  24. return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)
  25. def check_password(password, encoded, setter=None, preferred='default'):
  26. """
  27. Return a boolean of whether the raw password matches the three
  28. part encoded digest.
  29. If setter is specified, it'll be called when you need to
  30. regenerate the password.
  31. """
  32. if password is None or not is_password_usable(encoded):
  33. return False
  34. preferred = get_hasher(preferred)
  35. try:
  36. hasher = identify_hasher(encoded)
  37. except ValueError:
  38. # encoded is gibberish or uses a hasher that's no longer installed.
  39. return False
  40. hasher_changed = hasher.algorithm != preferred.algorithm
  41. must_update = hasher_changed or preferred.must_update(encoded)
  42. is_correct = hasher.verify(password, encoded)
  43. # If the hasher didn't change (we don't protect against enumeration if it
  44. # does) and the password should get updated, try to close the timing gap
  45. # between the work factor of the current encoded password and the default
  46. # work factor.
  47. if not is_correct and not hasher_changed and must_update:
  48. hasher.harden_runtime(password, encoded)
  49. if setter and is_correct and must_update:
  50. setter(password)
  51. return is_correct
  52. def make_password(password, salt=None, hasher='default'):
  53. """
  54. Turn a plain-text password into a hash for database storage
  55. Same as encode() but generate a new random salt. If password is None then
  56. return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
  57. which disallows logins. Additional random string reduces chances of gaining
  58. access to staff or superuser accounts. See ticket #20079 for more info.
  59. """
  60. if password is None:
  61. return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
  62. if not isinstance(password, (bytes, str)):
  63. raise TypeError(
  64. 'Password must be a string or bytes, got %s.'
  65. % type(password).__qualname__
  66. )
  67. hasher = get_hasher(hasher)
  68. salt = salt or hasher.salt()
  69. return hasher.encode(password, salt)
  70. @functools.lru_cache()
  71. def get_hashers():
  72. hashers = []
  73. for hasher_path in settings.PASSWORD_HASHERS:
  74. hasher_cls = import_string(hasher_path)
  75. hasher = hasher_cls()
  76. if not getattr(hasher, 'algorithm'):
  77. raise ImproperlyConfigured("hasher doesn't specify an "
  78. "algorithm name: %s" % hasher_path)
  79. hashers.append(hasher)
  80. return hashers
  81. @functools.lru_cache()
  82. def get_hashers_by_algorithm():
  83. return {hasher.algorithm: hasher for hasher in get_hashers()}
  84. @receiver(setting_changed)
  85. def reset_hashers(**kwargs):
  86. if kwargs['setting'] == 'PASSWORD_HASHERS':
  87. get_hashers.cache_clear()
  88. get_hashers_by_algorithm.cache_clear()
  89. def get_hasher(algorithm='default'):
  90. """
  91. Return an instance of a loaded password hasher.
  92. If algorithm is 'default', return the default hasher. Lazily import hashers
  93. specified in the project's settings file if needed.
  94. """
  95. if hasattr(algorithm, 'algorithm'):
  96. return algorithm
  97. elif algorithm == 'default':
  98. return get_hashers()[0]
  99. else:
  100. hashers = get_hashers_by_algorithm()
  101. try:
  102. return hashers[algorithm]
  103. except KeyError:
  104. raise ValueError("Unknown password hashing algorithm '%s'. "
  105. "Did you specify it in the PASSWORD_HASHERS "
  106. "setting?" % algorithm)
  107. def identify_hasher(encoded):
  108. """
  109. Return an instance of a loaded password hasher.
  110. Identify hasher algorithm by examining encoded hash, and call
  111. get_hasher() to return hasher. Raise ValueError if
  112. algorithm cannot be identified, or if hasher is not loaded.
  113. """
  114. # Ancient versions of Django created plain MD5 passwords and accepted
  115. # MD5 passwords with an empty salt.
  116. if ((len(encoded) == 32 and '$' not in encoded) or
  117. (len(encoded) == 37 and encoded.startswith('md5$$'))):
  118. algorithm = 'unsalted_md5'
  119. # Ancient versions of Django accepted SHA1 passwords with an empty salt.
  120. elif len(encoded) == 46 and encoded.startswith('sha1$$'):
  121. algorithm = 'unsalted_sha1'
  122. else:
  123. algorithm = encoded.split('$', 1)[0]
  124. return get_hasher(algorithm)
  125. def mask_hash(hash, show=6, char="*"):
  126. """
  127. Return the given hash, with only the first ``show`` number shown. The
  128. rest are masked with ``char`` for security reasons.
  129. """
  130. masked = hash[:show]
  131. masked += char * len(hash[show:])
  132. return masked
  133. def must_update_salt(salt, expected_entropy):
  134. # Each character in the salt provides log_2(len(alphabet)) bits of entropy.
  135. return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy
  136. class BasePasswordHasher:
  137. """
  138. Abstract base class for password hashers
  139. When creating your own hasher, you need to override algorithm,
  140. verify(), encode() and safe_summary().
  141. PasswordHasher objects are immutable.
  142. """
  143. algorithm = None
  144. library = None
  145. salt_entropy = 128
  146. def _load_library(self):
  147. if self.library is not None:
  148. if isinstance(self.library, (tuple, list)):
  149. name, mod_path = self.library
  150. else:
  151. mod_path = self.library
  152. try:
  153. module = importlib.import_module(mod_path)
  154. except ImportError as e:
  155. raise ValueError("Couldn't load %r algorithm library: %s" %
  156. (self.__class__.__name__, e))
  157. return module
  158. raise ValueError("Hasher %r doesn't specify a library attribute" %
  159. self.__class__.__name__)
  160. def salt(self):
  161. """
  162. Generate a cryptographically secure nonce salt in ASCII with an entropy
  163. of at least `salt_entropy` bits.
  164. """
  165. # Each character in the salt provides
  166. # log_2(len(alphabet)) bits of entropy.
  167. char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS)))
  168. return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS)
  169. def verify(self, password, encoded):
  170. """Check if the given password is correct."""
  171. raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')
  172. def encode(self, password, salt):
  173. """
  174. Create an encoded database value.
  175. The result is normally formatted as "algorithm$salt$hash" and
  176. must be fewer than 128 characters.
  177. """
  178. raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method')
  179. def decode(self, encoded):
  180. """
  181. Return a decoded database value.
  182. The result is a dictionary and should contain `algorithm`, `hash`, and
  183. `salt`. Extra keys can be algorithm specific like `iterations` or
  184. `work_factor`.
  185. """
  186. raise NotImplementedError(
  187. 'subclasses of BasePasswordHasher must provide a decode() method.'
  188. )
  189. def safe_summary(self, encoded):
  190. """
  191. Return a summary of safe values.
  192. The result is a dictionary and will be used where the password field
  193. must be displayed to construct a safe representation of the password.
  194. """
  195. raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method')
  196. def must_update(self, encoded):
  197. return False
  198. def harden_runtime(self, password, encoded):
  199. """
  200. Bridge the runtime gap between the work factor supplied in `encoded`
  201. and the work factor suggested by this hasher.
  202. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
  203. `self.iterations` is 30000, this method should run password through
  204. another 10000 iterations of PBKDF2. Similar approaches should exist
  205. for any hasher that has a work factor. If not, this method should be
  206. defined as a no-op to silence the warning.
  207. """
  208. warnings.warn('subclasses of BasePasswordHasher should provide a harden_runtime() method')
  209. class PBKDF2PasswordHasher(BasePasswordHasher):
  210. """
  211. Secure password hashing using the PBKDF2 algorithm (recommended)
  212. Configured to use PBKDF2 + HMAC + SHA256.
  213. The result is a 64 byte binary string. Iterations may be changed
  214. safely but you must rename the algorithm if you change SHA256.
  215. """
  216. algorithm = "pbkdf2_sha256"
  217. iterations = 260000
  218. digest = hashlib.sha256
  219. def encode(self, password, salt, iterations=None):
  220. assert password is not None
  221. assert salt and '$' not in salt
  222. iterations = iterations or self.iterations
  223. hash = pbkdf2(password, salt, iterations, digest=self.digest)
  224. hash = base64.b64encode(hash).decode('ascii').strip()
  225. return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
  226. def decode(self, encoded):
  227. algorithm, iterations, salt, hash = encoded.split('$', 3)
  228. assert algorithm == self.algorithm
  229. return {
  230. 'algorithm': algorithm,
  231. 'hash': hash,
  232. 'iterations': int(iterations),
  233. 'salt': salt,
  234. }
  235. def verify(self, password, encoded):
  236. decoded = self.decode(encoded)
  237. encoded_2 = self.encode(password, decoded['salt'], decoded['iterations'])
  238. return constant_time_compare(encoded, encoded_2)
  239. def safe_summary(self, encoded):
  240. decoded = self.decode(encoded)
  241. return {
  242. _('algorithm'): decoded['algorithm'],
  243. _('iterations'): decoded['iterations'],
  244. _('salt'): mask_hash(decoded['salt']),
  245. _('hash'): mask_hash(decoded['hash']),
  246. }
  247. def must_update(self, encoded):
  248. decoded = self.decode(encoded)
  249. update_salt = must_update_salt(decoded['salt'], self.salt_entropy)
  250. return (decoded['iterations'] != self.iterations) or update_salt
  251. def harden_runtime(self, password, encoded):
  252. decoded = self.decode(encoded)
  253. extra_iterations = self.iterations - decoded['iterations']
  254. if extra_iterations > 0:
  255. self.encode(password, decoded['salt'], extra_iterations)
  256. class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
  257. """
  258. Alternate PBKDF2 hasher which uses SHA1, the default PRF
  259. recommended by PKCS #5. This is compatible with other
  260. implementations of PBKDF2, such as openssl's
  261. PKCS5_PBKDF2_HMAC_SHA1().
  262. """
  263. algorithm = "pbkdf2_sha1"
  264. digest = hashlib.sha1
  265. class Argon2PasswordHasher(BasePasswordHasher):
  266. """
  267. Secure password hashing using the argon2 algorithm.
  268. This is the winner of the Password Hashing Competition 2013-2015
  269. (https://password-hashing.net). It requires the argon2-cffi library which
  270. depends on native C code and might cause portability issues.
  271. """
  272. algorithm = 'argon2'
  273. library = 'argon2'
  274. time_cost = 2
  275. memory_cost = 102400
  276. parallelism = 8
  277. def encode(self, password, salt):
  278. argon2 = self._load_library()
  279. params = self.params()
  280. data = argon2.low_level.hash_secret(
  281. password.encode(),
  282. salt.encode(),
  283. time_cost=params.time_cost,
  284. memory_cost=params.memory_cost,
  285. parallelism=params.parallelism,
  286. hash_len=params.hash_len,
  287. type=params.type,
  288. )
  289. return self.algorithm + data.decode('ascii')
  290. def decode(self, encoded):
  291. argon2 = self._load_library()
  292. algorithm, rest = encoded.split('$', 1)
  293. assert algorithm == self.algorithm
  294. params = argon2.extract_parameters('$' + rest)
  295. variety, *_, b64salt, hash = rest.split('$')
  296. # Add padding.
  297. b64salt += '=' * (-len(b64salt) % 4)
  298. salt = base64.b64decode(b64salt).decode('latin1')
  299. return {
  300. 'algorithm': algorithm,
  301. 'hash': hash,
  302. 'memory_cost': params.memory_cost,
  303. 'parallelism': params.parallelism,
  304. 'salt': salt,
  305. 'time_cost': params.time_cost,
  306. 'variety': variety,
  307. 'version': params.version,
  308. 'params': params,
  309. }
  310. def verify(self, password, encoded):
  311. argon2 = self._load_library()
  312. algorithm, rest = encoded.split('$', 1)
  313. assert algorithm == self.algorithm
  314. try:
  315. return argon2.PasswordHasher().verify('$' + rest, password)
  316. except argon2.exceptions.VerificationError:
  317. return False
  318. def safe_summary(self, encoded):
  319. decoded = self.decode(encoded)
  320. return {
  321. _('algorithm'): decoded['algorithm'],
  322. _('variety'): decoded['variety'],
  323. _('version'): decoded['version'],
  324. _('memory cost'): decoded['memory_cost'],
  325. _('time cost'): decoded['time_cost'],
  326. _('parallelism'): decoded['parallelism'],
  327. _('salt'): mask_hash(decoded['salt']),
  328. _('hash'): mask_hash(decoded['hash']),
  329. }
  330. def must_update(self, encoded):
  331. decoded = self.decode(encoded)
  332. current_params = decoded['params']
  333. new_params = self.params()
  334. # Set salt_len to the salt_len of the current parameters because salt
  335. # is explicitly passed to argon2.
  336. new_params.salt_len = current_params.salt_len
  337. update_salt = must_update_salt(decoded['salt'], self.salt_entropy)
  338. return (current_params != new_params) or update_salt
  339. def harden_runtime(self, password, encoded):
  340. # The runtime for Argon2 is too complicated to implement a sensible
  341. # hardening algorithm.
  342. pass
  343. def params(self):
  344. argon2 = self._load_library()
  345. # salt_len is a noop, because we provide our own salt.
  346. return argon2.Parameters(
  347. type=argon2.low_level.Type.ID,
  348. version=argon2.low_level.ARGON2_VERSION,
  349. salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH,
  350. hash_len=argon2.DEFAULT_HASH_LENGTH,
  351. time_cost=self.time_cost,
  352. memory_cost=self.memory_cost,
  353. parallelism=self.parallelism,
  354. )
  355. class BCryptSHA256PasswordHasher(BasePasswordHasher):
  356. """
  357. Secure password hashing using the bcrypt algorithm (recommended)
  358. This is considered by many to be the most secure algorithm but you
  359. must first install the bcrypt library. Please be warned that
  360. this library depends on native C code and might cause portability
  361. issues.
  362. """
  363. algorithm = "bcrypt_sha256"
  364. digest = hashlib.sha256
  365. library = ("bcrypt", "bcrypt")
  366. rounds = 12
  367. def salt(self):
  368. bcrypt = self._load_library()
  369. return bcrypt.gensalt(self.rounds)
  370. def encode(self, password, salt):
  371. bcrypt = self._load_library()
  372. password = password.encode()
  373. # Hash the password prior to using bcrypt to prevent password
  374. # truncation as described in #20138.
  375. if self.digest is not None:
  376. # Use binascii.hexlify() because a hex encoded bytestring is str.
  377. password = binascii.hexlify(self.digest(password).digest())
  378. data = bcrypt.hashpw(password, salt)
  379. return "%s$%s" % (self.algorithm, data.decode('ascii'))
  380. def decode(self, encoded):
  381. algorithm, empty, algostr, work_factor, data = encoded.split('$', 4)
  382. assert algorithm == self.algorithm
  383. return {
  384. 'algorithm': algorithm,
  385. 'algostr': algostr,
  386. 'checksum': data[22:],
  387. 'salt': data[:22],
  388. 'work_factor': int(work_factor),
  389. }
  390. def verify(self, password, encoded):
  391. algorithm, data = encoded.split('$', 1)
  392. assert algorithm == self.algorithm
  393. encoded_2 = self.encode(password, data.encode('ascii'))
  394. return constant_time_compare(encoded, encoded_2)
  395. def safe_summary(self, encoded):
  396. decoded = self.decode(encoded)
  397. return {
  398. _('algorithm'): decoded['algorithm'],
  399. _('work factor'): decoded['work_factor'],
  400. _('salt'): mask_hash(decoded['salt']),
  401. _('checksum'): mask_hash(decoded['checksum']),
  402. }
  403. def must_update(self, encoded):
  404. decoded = self.decode(encoded)
  405. return decoded['work_factor'] != self.rounds
  406. def harden_runtime(self, password, encoded):
  407. _, data = encoded.split('$', 1)
  408. salt = data[:29] # Length of the salt in bcrypt.
  409. rounds = data.split('$')[2]
  410. # work factor is logarithmic, adding one doubles the load.
  411. diff = 2**(self.rounds - int(rounds)) - 1
  412. while diff > 0:
  413. self.encode(password, salt.encode('ascii'))
  414. diff -= 1
  415. class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
  416. """
  417. Secure password hashing using the bcrypt algorithm
  418. This is considered by many to be the most secure algorithm but you
  419. must first install the bcrypt library. Please be warned that
  420. this library depends on native C code and might cause portability
  421. issues.
  422. This hasher does not first hash the password which means it is subject to
  423. bcrypt's 72 bytes password truncation. Most use cases should prefer the
  424. BCryptSHA256PasswordHasher.
  425. """
  426. algorithm = "bcrypt"
  427. digest = None
  428. class SHA1PasswordHasher(BasePasswordHasher):
  429. """
  430. The SHA1 password hashing algorithm (not recommended)
  431. """
  432. algorithm = "sha1"
  433. def encode(self, password, salt):
  434. assert password is not None
  435. assert salt and '$' not in salt
  436. hash = hashlib.sha1((salt + password).encode()).hexdigest()
  437. return "%s$%s$%s" % (self.algorithm, salt, hash)
  438. def decode(self, encoded):
  439. algorithm, salt, hash = encoded.split('$', 2)
  440. assert algorithm == self.algorithm
  441. return {
  442. 'algorithm': algorithm,
  443. 'hash': hash,
  444. 'salt': salt,
  445. }
  446. def verify(self, password, encoded):
  447. decoded = self.decode(encoded)
  448. encoded_2 = self.encode(password, decoded['salt'])
  449. return constant_time_compare(encoded, encoded_2)
  450. def safe_summary(self, encoded):
  451. decoded = self.decode(encoded)
  452. return {
  453. _('algorithm'): decoded['algorithm'],
  454. _('salt'): mask_hash(decoded['salt'], show=2),
  455. _('hash'): mask_hash(decoded['hash']),
  456. }
  457. def must_update(self, encoded):
  458. decoded = self.decode(encoded)
  459. return must_update_salt(decoded['salt'], self.salt_entropy)
  460. def harden_runtime(self, password, encoded):
  461. pass
  462. class MD5PasswordHasher(BasePasswordHasher):
  463. """
  464. The Salted MD5 password hashing algorithm (not recommended)
  465. """
  466. algorithm = "md5"
  467. def encode(self, password, salt):
  468. assert password is not None
  469. assert salt and '$' not in salt
  470. hash = hashlib.md5((salt + password).encode()).hexdigest()
  471. return "%s$%s$%s" % (self.algorithm, salt, hash)
  472. def decode(self, encoded):
  473. algorithm, salt, hash = encoded.split('$', 2)
  474. assert algorithm == self.algorithm
  475. return {
  476. 'algorithm': algorithm,
  477. 'hash': hash,
  478. 'salt': salt,
  479. }
  480. def verify(self, password, encoded):
  481. decoded = self.decode(encoded)
  482. encoded_2 = self.encode(password, decoded['salt'])
  483. return constant_time_compare(encoded, encoded_2)
  484. def safe_summary(self, encoded):
  485. decoded = self.decode(encoded)
  486. return {
  487. _('algorithm'): decoded['algorithm'],
  488. _('salt'): mask_hash(decoded['salt'], show=2),
  489. _('hash'): mask_hash(decoded['hash']),
  490. }
  491. def must_update(self, encoded):
  492. decoded = self.decode(encoded)
  493. return must_update_salt(decoded['salt'], self.salt_entropy)
  494. def harden_runtime(self, password, encoded):
  495. pass
  496. class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
  497. """
  498. Very insecure algorithm that you should *never* use; store SHA1 hashes
  499. with an empty salt.
  500. This class is implemented because Django used to accept such password
  501. hashes. Some older Django installs still have these values lingering
  502. around so we need to handle and upgrade them properly.
  503. """
  504. algorithm = "unsalted_sha1"
  505. def salt(self):
  506. return ''
  507. def encode(self, password, salt):
  508. assert salt == ''
  509. hash = hashlib.sha1(password.encode()).hexdigest()
  510. return 'sha1$$%s' % hash
  511. def decode(self, encoded):
  512. assert encoded.startswith('sha1$$')
  513. return {
  514. 'algorithm': self.algorithm,
  515. 'hash': encoded[6:],
  516. 'salt': None,
  517. }
  518. def verify(self, password, encoded):
  519. encoded_2 = self.encode(password, '')
  520. return constant_time_compare(encoded, encoded_2)
  521. def safe_summary(self, encoded):
  522. decoded = self.decode(encoded)
  523. return {
  524. _('algorithm'): decoded['algorithm'],
  525. _('hash'): mask_hash(decoded['hash']),
  526. }
  527. def harden_runtime(self, password, encoded):
  528. pass
  529. class UnsaltedMD5PasswordHasher(BasePasswordHasher):
  530. """
  531. Incredibly insecure algorithm that you should *never* use; stores unsalted
  532. MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an
  533. empty salt.
  534. This class is implemented because Django used to store passwords this way
  535. and to accept such password hashes. Some older Django installs still have
  536. these values lingering around so we need to handle and upgrade them
  537. properly.
  538. """
  539. algorithm = "unsalted_md5"
  540. def salt(self):
  541. return ''
  542. def encode(self, password, salt):
  543. assert salt == ''
  544. return hashlib.md5(password.encode()).hexdigest()
  545. def decode(self, encoded):
  546. return {
  547. 'algorithm': self.algorithm,
  548. 'hash': encoded,
  549. 'salt': None,
  550. }
  551. def verify(self, password, encoded):
  552. if len(encoded) == 37 and encoded.startswith('md5$$'):
  553. encoded = encoded[5:]
  554. encoded_2 = self.encode(password, '')
  555. return constant_time_compare(encoded, encoded_2)
  556. def safe_summary(self, encoded):
  557. decoded = self.decode(encoded)
  558. return {
  559. _('algorithm'): decoded['algorithm'],
  560. _('hash'): mask_hash(decoded['hash'], show=3),
  561. }
  562. def harden_runtime(self, password, encoded):
  563. pass
  564. class CryptPasswordHasher(BasePasswordHasher):
  565. """
  566. Password hashing using UNIX crypt (not recommended)
  567. The crypt module is not supported on all platforms.
  568. """
  569. algorithm = "crypt"
  570. library = "crypt"
  571. def salt(self):
  572. return get_random_string(2)
  573. def encode(self, password, salt):
  574. crypt = self._load_library()
  575. assert len(salt) == 2
  576. hash = crypt.crypt(password, salt)
  577. assert hash is not None # A platform like OpenBSD with a dummy crypt module.
  578. # we don't need to store the salt, but Django used to do this
  579. return '%s$%s$%s' % (self.algorithm, '', hash)
  580. def decode(self, encoded):
  581. algorithm, salt, hash = encoded.split('$', 2)
  582. assert algorithm == self.algorithm
  583. return {
  584. 'algorithm': algorithm,
  585. 'hash': hash,
  586. 'salt': salt,
  587. }
  588. def verify(self, password, encoded):
  589. crypt = self._load_library()
  590. decoded = self.decode(encoded)
  591. data = crypt.crypt(password, decoded['hash'])
  592. return constant_time_compare(decoded['hash'], data)
  593. def safe_summary(self, encoded):
  594. decoded = self.decode(encoded)
  595. return {
  596. _('algorithm'): decoded['algorithm'],
  597. _('salt'): decoded['salt'],
  598. _('hash'): mask_hash(decoded['hash'], show=3),
  599. }
  600. def harden_runtime(self, password, encoded):
  601. pass