passlib 1.9.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. passlib/__init__.py +3 -0
  2. passlib/_data/wordsets/bip39.txt +2049 -0
  3. passlib/_data/wordsets/eff_long.txt +7776 -0
  4. passlib/_data/wordsets/eff_prefixed.txt +1296 -0
  5. passlib/_data/wordsets/eff_short.txt +1296 -0
  6. passlib/_logging.py +3 -0
  7. passlib/_protocols.py +33 -0
  8. passlib/apache.py +1106 -0
  9. passlib/apps.py +215 -0
  10. passlib/context.py +1944 -0
  11. passlib/crypto/__init__.py +1 -0
  12. passlib/crypto/_blowfish/__init__.py +153 -0
  13. passlib/crypto/_blowfish/_gen_files.py +238 -0
  14. passlib/crypto/_blowfish/base.py +1212 -0
  15. passlib/crypto/_blowfish/unrolled.py +1664 -0
  16. passlib/crypto/_md4.py +229 -0
  17. passlib/crypto/des.py +2250 -0
  18. passlib/crypto/digest.py +760 -0
  19. passlib/crypto/scrypt/__init__.py +273 -0
  20. passlib/crypto/scrypt/_builtin.py +220 -0
  21. passlib/crypto/scrypt/_gen_files.py +142 -0
  22. passlib/crypto/scrypt/_salsa.py +180 -0
  23. passlib/exc.py +409 -0
  24. passlib/ext/__init__.py +1 -0
  25. passlib/ext/django/__init__.py +6 -0
  26. passlib/ext/django/models.py +21 -0
  27. passlib/ext/django/utils.py +1181 -0
  28. passlib/handlers/__init__.py +1 -0
  29. passlib/handlers/argon2.py +999 -0
  30. passlib/handlers/bcrypt.py +996 -0
  31. passlib/handlers/cisco.py +396 -0
  32. passlib/handlers/des_crypt.py +504 -0
  33. passlib/handlers/digests.py +149 -0
  34. passlib/handlers/django.py +510 -0
  35. passlib/handlers/fshp.py +185 -0
  36. passlib/handlers/ldap_digests.py +356 -0
  37. passlib/handlers/md5_crypt.py +286 -0
  38. passlib/handlers/misc.py +201 -0
  39. passlib/handlers/mssql.py +217 -0
  40. passlib/handlers/mysql.py +92 -0
  41. passlib/handlers/oracle.py +137 -0
  42. passlib/handlers/pbkdf2.py +454 -0
  43. passlib/handlers/phpass.py +110 -0
  44. passlib/handlers/postgres.py +34 -0
  45. passlib/handlers/roundup.py +18 -0
  46. passlib/handlers/scram.py +532 -0
  47. passlib/handlers/scrypt.py +357 -0
  48. passlib/handlers/sha1_crypt.py +121 -0
  49. passlib/handlers/sha2_crypt.py +562 -0
  50. passlib/handlers/sun_md5_crypt.py +334 -0
  51. passlib/handlers/windows.py +299 -0
  52. passlib/hash.py +106 -0
  53. passlib/hosts.py +85 -0
  54. passlib/ifc.py +307 -0
  55. passlib/pwd.py +709 -0
  56. passlib/registry.py +547 -0
  57. passlib/totp.py +1852 -0
  58. passlib/utils/__init__.py +901 -0
  59. passlib/utils/binary.py +852 -0
  60. passlib/utils/compat/__init__.py +141 -0
  61. passlib/utils/decor.py +220 -0
  62. passlib/utils/des.py +31 -0
  63. passlib/utils/handlers.py +2616 -0
  64. passlib/utils/md4.py +25 -0
  65. passlib/utils/pbkdf2.py +172 -0
  66. passlib-1.9.5.dist-info/METADATA +90 -0
  67. passlib-1.9.5.dist-info/RECORD +69 -0
  68. passlib-1.9.5.dist-info/WHEEL +4 -0
  69. passlib-1.9.5.dist-info/licenses/LICENSE +116 -0
passlib/pwd.py ADDED
@@ -0,0 +1,709 @@
1
+ import codecs
2
+ import contextlib
3
+ import os
4
+ from collections import defaultdict
5
+ from collections.abc import Hashable, MutableMapping
6
+ from importlib import resources
7
+ from math import ceil, log2
8
+
9
+ from passlib import exc
10
+ from passlib._logging import logger
11
+ from passlib.utils import getrandstr, rng, to_unicode
12
+ from passlib.utils.decor import memoized_property
13
+
14
+ # local
15
+ __all__ = [
16
+ "genword",
17
+ "default_charsets",
18
+ "genphrase",
19
+ "default_wordsets",
20
+ ]
21
+
22
+ # XXX: rename / publically document this map?
23
+ entropy_aliases = dict(
24
+ # barest protection from throttled online attack
25
+ unsafe=12,
26
+ # some protection from unthrottled online attack
27
+ weak=24,
28
+ # some protection from offline attacks
29
+ fair=36,
30
+ # reasonable protection from offline attacks
31
+ strong=48,
32
+ # very good protection from offline attacks
33
+ secure=60,
34
+ )
35
+
36
+
37
+ def _superclasses(obj, cls):
38
+ """return remaining classes in object's MRO after cls"""
39
+ mro = type(obj).__mro__
40
+ return mro[mro.index(cls) + 1 :]
41
+
42
+
43
+ def _self_info_rate(source):
44
+ """
45
+ returns 'rate of self-information' --
46
+ i.e. average (per-symbol) entropy of the sequence **source**,
47
+ where probability of a given symbol occurring is calculated based on
48
+ the number of occurrences within the sequence itself.
49
+
50
+ if all elements of the source are unique, this should equal ``log(len(source), 2)``.
51
+
52
+ :arg source:
53
+ iterable containing 0+ symbols
54
+ (e.g. list of strings or ints, string of characters, etc).
55
+
56
+ :returns:
57
+ float bits of entropy
58
+ """
59
+ try:
60
+ size = len(source)
61
+ except TypeError:
62
+ # if len() doesn't work, calculate size by summing counts later
63
+ size = None
64
+ counts = defaultdict(int)
65
+ for char in source:
66
+ counts[char] += 1
67
+ if size is None:
68
+ values = counts.values()
69
+ size = sum(values)
70
+ else:
71
+ values = counts.values()
72
+ if not size:
73
+ return 0
74
+ # NOTE: the following performs ``- sum(value / size * logf(value / size, 2) for value in values)``,
75
+ # it just does so with as much pulled out of the sum() loop as possible...
76
+ return log2(size) - sum(value * log2(value) for value in values) / size
77
+
78
+
79
+ # def _total_self_info(source):
80
+ # """
81
+ # return total self-entropy of a sequence
82
+ # (the average entropy per symbol * size of sequence)
83
+ # """
84
+ # return _self_info_rate(source) * len(source)
85
+
86
+
87
+ def _open_asset_path(path, encoding=None):
88
+ """
89
+ :param asset_path:
90
+ string containing absolute path to file,
91
+ or package-relative path using format
92
+ ``"python.module:relative/file/path"``.
93
+
94
+ :returns:
95
+ filehandle opened in 'rb' mode
96
+ (unless encoding explicitly specified)
97
+ """
98
+ if encoding:
99
+ return codecs.getreader(encoding)(_open_asset_path(path))
100
+ if os.path.isabs(path):
101
+ return open(path, "rb") # noqa: SIM115
102
+ package, sep, subpath = path.partition(":")
103
+ if not sep:
104
+ raise ValueError(
105
+ "asset path must be absolute file path "
106
+ f"or use 'pkg.name:sub/path' format: {path!r}"
107
+ )
108
+ return resources.files(package).joinpath(subpath).open("rb")
109
+
110
+
111
+ #: type aliases
112
+ _sequence_types = (list, tuple)
113
+ _set_types = (set, frozenset)
114
+
115
+ #: set of elements that ensure_unique() has validated already.
116
+ _ensure_unique_cache: set[Hashable] = set()
117
+
118
+
119
+ def _ensure_unique(source, param="source"):
120
+ """
121
+ helper for generators --
122
+ Throws ValueError if source elements aren't unique.
123
+ Error message will display (abbreviated) repr of the duplicates in a string/list
124
+ """
125
+ # check cache to speed things up for frozensets / tuples / strings
126
+ cache = _ensure_unique_cache
127
+ hashable = True
128
+ try:
129
+ if source in cache:
130
+ return True
131
+ except TypeError:
132
+ hashable = False
133
+
134
+ # check if it has dup elements
135
+ if isinstance(source, _set_types) or len(set(source)) == len(source):
136
+ if hashable:
137
+ with contextlib.suppress(TypeError):
138
+ # XXX: under pypy, "list() in set()" above doesn't throw TypeError,
139
+ # but trying to add unhashable it to a set *does*.
140
+ cache.add(source)
141
+ return True
142
+
143
+ # build list of duplicate values
144
+ seen = set()
145
+ dups = set()
146
+ for elem in source:
147
+ (dups if elem in seen else seen).add(elem)
148
+ dups = sorted(dups)
149
+ trunc = 8
150
+ if len(dups) > trunc:
151
+ trunc = 5
152
+ dup_repr = ", ".join(repr(str(word)) for word in dups[:trunc])
153
+ if len(dups) > trunc:
154
+ dup_repr += ", ... plus %d others" % (len(dups) - trunc)
155
+
156
+ # throw error
157
+ raise ValueError(f"`{param}` cannot contain duplicate elements: {dup_repr}")
158
+
159
+
160
+ class SequenceGenerator:
161
+ """
162
+ Base class used by word & phrase generators.
163
+
164
+ These objects take a series of options, corresponding
165
+ to those of the :func:`generate` function.
166
+ They act as callables which can be used to generate a password
167
+ or a list of 1+ passwords. They also expose some read-only
168
+ informational attributes.
169
+
170
+ Parameters
171
+ ----------
172
+ :param entropy:
173
+ Optionally specify the amount of entropy the resulting passwords
174
+ should contain (as measured with respect to the generator itself).
175
+ This will be used to auto-calculate the required password size.
176
+
177
+ :param length:
178
+ Optionally specify the length of password to generate,
179
+ measured as count of whatever symbols the subclass uses (characters or words).
180
+ Note if ``entropy`` requires a larger minimum length,
181
+ that will be used instead.
182
+
183
+ :param rng:
184
+ Optionally provide a custom RNG source to use.
185
+ Should be an instance of :class:`random.Random`,
186
+ defaults to :class:`random.SystemRandom`.
187
+
188
+ Attributes
189
+ ----------
190
+ .. autoattribute:: length
191
+ .. autoattribute:: symbol_count
192
+ .. autoattribute:: entropy_per_symbol
193
+ .. autoattribute:: entropy
194
+
195
+ Subclassing
196
+ -----------
197
+ Subclasses must implement the ``.__next__()`` method,
198
+ and set ``.symbol_count`` before calling base ``__init__`` method.
199
+ """
200
+
201
+ #: requested size of final password
202
+ length = None
203
+
204
+ #: requested entropy of final password
205
+ requested_entropy = "strong"
206
+
207
+ #: random number source to use
208
+ rng = rng
209
+
210
+ #: number of potential symbols (must be filled in by subclass)
211
+ symbol_count = None
212
+
213
+ def __init__(self, entropy=None, length=None, rng=None, **kwds):
214
+ # make sure subclass set things up correctly
215
+ assert self.symbol_count is not None, "subclass must set .symbol_count"
216
+
217
+ # init length & requested entropy
218
+ if entropy is not None or length is None:
219
+ if entropy is None:
220
+ entropy = self.requested_entropy
221
+ entropy = entropy_aliases.get(entropy, entropy)
222
+ if entropy <= 0:
223
+ raise ValueError("`entropy` must be positive number")
224
+ min_length = int(ceil(entropy / self.entropy_per_symbol))
225
+ if length is None or length < min_length:
226
+ length = min_length
227
+
228
+ self.requested_entropy = entropy
229
+
230
+ if length < 1:
231
+ raise ValueError("`length` must be positive integer")
232
+ self.length = length
233
+
234
+ # init other common options
235
+ if rng is not None:
236
+ self.rng = rng
237
+
238
+ # hand off to parent
239
+ if kwds and _superclasses(self, SequenceGenerator) == (object,):
240
+ raise TypeError("Unexpected keyword(s): {}".format(", ".join(kwds.keys())))
241
+ super().__init__(**kwds)
242
+
243
+ @memoized_property
244
+ def entropy_per_symbol(self):
245
+ """
246
+ Average entropy per symbol (assuming all symbols have equal probability)
247
+ """
248
+ return log2(self.symbol_count)
249
+
250
+ @memoized_property
251
+ def entropy(self):
252
+ """
253
+ Effective entropy of generated passwords.
254
+
255
+ This value will always be a multiple of :attr:`entropy_per_symbol`.
256
+ If entropy is specified in constructor, :attr:`length` will be chosen so
257
+ so that this value is the smallest multiple >= :attr:`requested_entropy`.
258
+ """
259
+ return self.length * self.entropy_per_symbol
260
+
261
+ def __next__(self):
262
+ """main generation function, should create one password/phrase"""
263
+ raise NotImplementedError("implement in subclass")
264
+
265
+ def __call__(self, returns=None):
266
+ """
267
+ frontend used by genword() / genphrase() to create passwords
268
+ """
269
+ if returns is None:
270
+ return next(self)
271
+ if isinstance(returns, int):
272
+ return [next(self) for _ in range(returns)]
273
+ if returns is iter:
274
+ return self
275
+ raise exc.ExpectedTypeError(returns, "<None>, int, or <iter>", "returns")
276
+
277
+ def __iter__(self):
278
+ return self
279
+
280
+
281
+ #: global dict of predefined characters sets
282
+ default_charsets = dict(
283
+ # ascii letters, digits, and some punctuation
284
+ ascii_72="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*?/",
285
+ # ascii letters and digits
286
+ ascii_62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
287
+ # ascii_50, without visually similar '1IiLl', '0Oo', '5S', '8B'
288
+ ascii_50="234679abcdefghjkmnpqrstuvwxyzACDEFGHJKMNPQRTUVWXYZ",
289
+ # lower case hexadecimal
290
+ hex="0123456789abcdef",
291
+ )
292
+
293
+
294
+ class WordGenerator(SequenceGenerator):
295
+ """
296
+ Class which generates passwords by randomly choosing from a string of unique characters.
297
+
298
+ Parameters
299
+ ----------
300
+ :param chars:
301
+ custom character string to draw from.
302
+
303
+ :param charset:
304
+ predefined charset to draw from.
305
+
306
+ :param \\*\\*kwds:
307
+ all other keywords passed to the :class:`SequenceGenerator` parent class.
308
+
309
+ Attributes
310
+ ----------
311
+ .. autoattribute:: chars
312
+ .. autoattribute:: charset
313
+ .. autoattribute:: default_charsets
314
+ """
315
+
316
+ #: Predefined character set in use (set to None for instances using custom 'chars')
317
+ charset = "ascii_62"
318
+
319
+ #: string of chars to draw from -- usually filled in from charset
320
+ chars = None
321
+
322
+ def __init__(self, chars=None, charset=None, **kwds):
323
+ # init chars and charset
324
+ if chars:
325
+ if charset:
326
+ raise TypeError("`chars` and `charset` are mutually exclusive")
327
+ else:
328
+ if not charset:
329
+ charset = self.charset
330
+ assert charset
331
+ chars = default_charsets[charset]
332
+ self.charset = charset
333
+ chars = to_unicode(chars, param="chars")
334
+ _ensure_unique(chars, param="chars")
335
+ self.chars = chars
336
+
337
+ # hand off to parent
338
+ super().__init__(**kwds)
339
+ # log.debug("WordGenerator(): entropy/char=%r", self.entropy_per_symbol)
340
+
341
+ @memoized_property
342
+ def symbol_count(self):
343
+ return len(self.chars)
344
+
345
+ def __next__(self):
346
+ # XXX: could do things like optionally ensure certain character groups
347
+ # (e.g. letters & punctuation) are included
348
+ return getrandstr(self.rng, self.chars, self.length)
349
+
350
+
351
+ def genword(entropy=None, length=None, returns=None, **kwds):
352
+ """Generate one or more random passwords.
353
+
354
+ This function uses :mod:`random.SystemRandom` to generate
355
+ one or more passwords using various character sets.
356
+ The complexity of the password can be specified
357
+ by size, or by the desired amount of entropy.
358
+
359
+ Usage Example::
360
+
361
+ >>> # generate a random alphanumeric string with 48 bits of entropy (the default)
362
+ >>> from passlib import pwd
363
+ >>> pwd.genword()
364
+ 'DnBHvDjMK6'
365
+
366
+ >>> # generate a random hexadecimal string with 52 bits of entropy
367
+ >>> pwd.genword(entropy=52, charset="hex")
368
+ '310f1a7ac793f'
369
+
370
+ :param entropy:
371
+ Strength of resulting password, measured in 'guessing entropy' bits.
372
+ An appropriate **length** value will be calculated
373
+ based on the requested entropy amount, and the size of the character set.
374
+
375
+ This can be a positive integer, or one of the following preset
376
+ strings: ``"weak"`` (24), ``"fair"`` (36),
377
+ ``"strong"`` (48), and ``"secure"`` (56).
378
+
379
+ If neither this or **length** is specified, **entropy** will default
380
+ to ``"strong"`` (48).
381
+
382
+ :param length:
383
+ Size of resulting password, measured in characters.
384
+ If omitted, the size is auto-calculated based on the **entropy** parameter.
385
+
386
+ If both **entropy** and **length** are specified,
387
+ the stronger value will be used.
388
+
389
+ :param returns:
390
+ Controls what this function returns:
391
+
392
+ * If ``None`` (the default), this function will generate a single password.
393
+ * If an integer, this function will return a list containing that many passwords.
394
+ * If the ``iter`` constant, will return an iterator that yields passwords.
395
+
396
+ :param chars:
397
+
398
+ Optionally specify custom string of characters to use when randomly
399
+ generating a password. This option cannot be combined with **charset**.
400
+
401
+ :param charset:
402
+
403
+ The predefined character set to draw from (if not specified by **chars**).
404
+ There are currently four presets available:
405
+
406
+ * ``"ascii_62"`` (the default) -- all digits and ascii upper & lowercase letters.
407
+ Provides ~5.95 entropy per character.
408
+
409
+ * ``"ascii_50"`` -- subset which excludes visually similar characters
410
+ (``1IiLl0Oo5S8B``). Provides ~5.64 entropy per character.
411
+
412
+ * ``"ascii_72"`` -- all digits and ascii upper & lowercase letters,
413
+ as well as some punctuation. Provides ~6.17 entropy per character.
414
+
415
+ * ``"hex"`` -- Lower case hexadecimal. Providers 4 bits of entropy per character.
416
+
417
+ :returns:
418
+ :class:`!str` string containing randomly generated password;
419
+ or list of 1+ passwords if :samp:`returns={int}` is specified.
420
+ """
421
+ gen = WordGenerator(length=length, entropy=entropy, **kwds)
422
+ return gen(returns)
423
+
424
+
425
+ def _load_wordset(asset_path):
426
+ """
427
+ load wordset from compressed datafile within package data.
428
+ file should be utf-8 encoded
429
+
430
+ :param asset_path:
431
+ string containing absolute path to wordset file,
432
+ or "python.module:relative/file/path".
433
+
434
+ :returns:
435
+ tuple of words, as loaded from specified words file.
436
+ """
437
+ # open resource file, convert to tuple of words (strip blank lines & ws)
438
+ with _open_asset_path(asset_path, "utf-8") as fh:
439
+ gen = (word.strip() for word in fh)
440
+ words = tuple(word for word in gen if word)
441
+
442
+ # NOTE: works but not used
443
+ # # detect if file uses "<int> <word>" format, and strip numeric prefix
444
+ # def extract(row):
445
+ # idx, word = row.replace("\t", " ").split(" ", 1)
446
+ # if not idx.isdigit():
447
+ # raise ValueError("row is not dice index + word")
448
+ # return word
449
+ # try:
450
+ # extract(words[-1])
451
+ # except ValueError:
452
+ # pass
453
+ # else:
454
+ # words = tuple(extract(word) for word in words)
455
+
456
+ logger.debug("loaded %d-element wordset from %r", len(words), asset_path)
457
+ return words
458
+
459
+
460
+ class WordsetDict(MutableMapping):
461
+ """
462
+ Special mapping used to store dictionary of wordsets.
463
+ Different from a regular dict in that some wordsets
464
+ may be lazy-loaded from an asset path.
465
+ """
466
+
467
+ #: dict of key -> asset path
468
+ paths = None
469
+
470
+ #: dict of key -> value
471
+ _loaded = None
472
+
473
+ def __init__(self, *args, **kwds):
474
+ self.paths = {}
475
+ self._loaded = {}
476
+ super().__init__(*args, **kwds)
477
+
478
+ def __getitem__(self, key):
479
+ try:
480
+ return self._loaded[key]
481
+ except KeyError:
482
+ pass
483
+ path = self.paths[key]
484
+ value = self._loaded[key] = _load_wordset(path)
485
+ return value
486
+
487
+ def set_path(self, key, path):
488
+ """
489
+ set asset path to lazy-load wordset from.
490
+ """
491
+ self.paths[key] = path
492
+
493
+ def __setitem__(self, key, value):
494
+ self._loaded[key] = value
495
+
496
+ def __delitem__(self, key):
497
+ if key in self:
498
+ del self._loaded[key]
499
+ self.paths.pop(key, None)
500
+ else:
501
+ del self.paths[key]
502
+
503
+ @property
504
+ def _keyset(self):
505
+ keys = set(self._loaded)
506
+ keys.update(self.paths)
507
+ return keys
508
+
509
+ def __iter__(self):
510
+ return iter(self._keyset)
511
+
512
+ def __len__(self):
513
+ return len(self._keyset)
514
+
515
+ # NOTE: speeds things up, and prevents contains from lazy-loading
516
+ def __contains__(self, key):
517
+ return key in self._loaded or key in self.paths
518
+
519
+
520
+ #: dict of predefined word sets.
521
+ #: key is name of wordset, value should be sequence of words.
522
+ default_wordsets = WordsetDict()
523
+
524
+ # register the wordsets built into passlib
525
+ for name in ["eff_long", "eff_short", "eff_prefixed", "bip39"]:
526
+ default_wordsets.set_path(name, f"passlib:_data/wordsets/{name}.txt")
527
+
528
+
529
+ class PhraseGenerator(SequenceGenerator):
530
+ """class which generates passphrases by randomly choosing
531
+ from a list of unique words.
532
+
533
+ :param wordset:
534
+ wordset to draw from.
535
+ :param preset:
536
+ name of preset wordlist to use instead of ``wordset``.
537
+ :param spaces:
538
+ whether to insert spaces between words in output (defaults to ``True``).
539
+ :param \\*\\*kwds:
540
+ all other keywords passed to the :class:`SequenceGenerator` parent class.
541
+
542
+ .. autoattribute:: wordset
543
+ """
544
+
545
+ #: predefined wordset to use
546
+ wordset = "eff_long"
547
+
548
+ #: list of words to draw from
549
+ words = None
550
+
551
+ #: separator to use when joining words
552
+ sep = " "
553
+
554
+ def __init__(self, wordset=None, words=None, sep=None, **kwds):
555
+ # load wordset
556
+ if words is not None:
557
+ if wordset is not None:
558
+ raise TypeError("`words` and `wordset` are mutually exclusive")
559
+ else:
560
+ if wordset is None:
561
+ wordset = self.wordset
562
+ assert wordset
563
+ words = default_wordsets[wordset]
564
+ self.wordset = wordset
565
+
566
+ # init words
567
+ if not isinstance(words, _sequence_types):
568
+ words = tuple(words)
569
+ _ensure_unique(words, param="words")
570
+ self.words = words
571
+
572
+ # init separator
573
+ if sep is None:
574
+ sep = self.sep
575
+ sep = to_unicode(sep, param="sep")
576
+ self.sep = sep
577
+
578
+ # hand off to parent
579
+ super().__init__(**kwds)
580
+ ##log.debug("PhraseGenerator(): entropy/word=%r entropy/char=%r min_chars=%r",
581
+ ## self.entropy_per_symbol, self.entropy_per_char, self.min_chars)
582
+
583
+ @memoized_property
584
+ def symbol_count(self):
585
+ return len(self.words)
586
+
587
+ def __next__(self):
588
+ words = (self.rng.choice(self.words) for _ in range(self.length))
589
+ return self.sep.join(words)
590
+
591
+
592
+ def genphrase(entropy=None, length=None, returns=None, **kwds):
593
+ """Generate one or more random password / passphrases.
594
+
595
+ This function uses :mod:`random.SystemRandom` to generate
596
+ one or more passwords; it can be configured to generate
597
+ alphanumeric passwords, or full english phrases.
598
+ The complexity of the password can be specified
599
+ by size, or by the desired amount of entropy.
600
+
601
+ Usage Example::
602
+
603
+ >>> # generate random phrase with 48 bits of entropy
604
+ >>> from passlib import pwd
605
+ >>> pwd.genphrase()
606
+ 'gangly robbing salt shove'
607
+
608
+ >>> # generate a random phrase with 52 bits of entropy
609
+ >>> # using a particular wordset
610
+ >>> pwd.genword(entropy=52, wordset="bip39")
611
+ 'wheat dilemma reward rescue diary'
612
+
613
+ :param entropy:
614
+ Strength of resulting password, measured in 'guessing entropy' bits.
615
+ An appropriate **length** value will be calculated
616
+ based on the requested entropy amount, and the size of the word set.
617
+
618
+ This can be a positive integer, or one of the following preset
619
+ strings: ``"weak"`` (24), ``"fair"`` (36),
620
+ ``"strong"`` (48), and ``"secure"`` (56).
621
+
622
+ If neither this or **length** is specified, **entropy** will default
623
+ to ``"strong"`` (48).
624
+
625
+ :param length:
626
+ Length of resulting password, measured in words.
627
+ If omitted, the size is auto-calculated based on the **entropy** parameter.
628
+
629
+ If both **entropy** and **length** are specified,
630
+ the stronger value will be used.
631
+
632
+ :param returns:
633
+ Controls what this function returns:
634
+
635
+ * If ``None`` (the default), this function will generate a single password.
636
+ * If an integer, this function will return a list containing that many passwords.
637
+ * If the ``iter`` builtin, will return an iterator that yields passwords.
638
+
639
+ :param words:
640
+
641
+ Optionally specifies a list/set of words to use when randomly generating a passphrase.
642
+ This option cannot be combined with **wordset**.
643
+
644
+ :param wordset:
645
+
646
+ The predefined word set to draw from (if not specified by **words**).
647
+ There are currently four presets available:
648
+
649
+ ``"eff_long"`` (the default)
650
+
651
+ Wordset containing 7776 english words of ~7 letters.
652
+ Constructed by the EFF, it offers ~12.9 bits of entropy per word.
653
+
654
+ This wordset (and the other ``"eff_"`` wordsets)
655
+ were `created by the EFF <https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases>`_
656
+ to aid in generating passwords. See their announcement page
657
+ for more details about the design & properties of these wordsets.
658
+
659
+ ``"eff_short"``
660
+
661
+ Wordset containing 1296 english words of ~4.5 letters.
662
+ Constructed by the EFF, it offers ~10.3 bits of entropy per word.
663
+
664
+ ``"eff_prefixed"``
665
+
666
+ Wordset containing 1296 english words of ~8 letters,
667
+ selected so that they each have a unique 3-character prefix.
668
+ Constructed by the EFF, it offers ~10.3 bits of entropy per word.
669
+
670
+ ``"bip39"``
671
+
672
+ Wordset of 2048 english words of ~5 letters,
673
+ selected so that they each have a unique 4-character prefix.
674
+ Published as part of Bitcoin's `BIP 39 <https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt>`_,
675
+ this wordset has exactly 11 bits of entropy per word.
676
+
677
+ This list offers words that are typically shorter than ``"eff_long"``
678
+ (at the cost of slightly less entropy); and much shorter than
679
+ ``"eff_prefixed"`` (at the cost of a longer unique prefix).
680
+
681
+ :param sep:
682
+ Optional separator to use when joining words.
683
+ Defaults to ``" "`` (a space), but can be an empty string, a hyphen, etc.
684
+
685
+ :returns:
686
+ :class:`!str` containing randomly generated passphrase;
687
+ or list of 1+ passphrases if :samp:`returns={int}` is specified.
688
+ """
689
+ gen = PhraseGenerator(entropy=entropy, length=length, **kwds)
690
+ return gen(returns)
691
+
692
+
693
+ # =============================================================================
694
+ # strength measurement
695
+ #
696
+ # NOTE:
697
+ # for a little while, had rough draft of password strength measurement alg here.
698
+ # but not sure if there's value in yet another measurement algorithm,
699
+ # that's not just duplicating the effort of libraries like zxcbn.
700
+ # may revive it later, but for now, leaving some refs to others out there:
701
+ # * NIST 800-63 has simple alg
702
+ # * zxcvbn (https://tech.dropbox.com/2012/04/zxcvbn-realistic-password-strength-estimation/)
703
+ # might also be good, and has approach similar to composite approach i was already thinking about,
704
+ # but much more well thought out.
705
+ # * passfault (https://github.com/c-a-m/passfault) looks thorough,
706
+ # but may have licensing issues, plus porting to python looks like very big job :(
707
+ # * give a look at running things through zlib - might be able to cheaply
708
+ # catch extra redundancies.
709
+ # =============================================================================