libpass 1.7.5.post0__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. libpass-1.7.5.post0.dist-info/METADATA +81 -0
  2. libpass-1.7.5.post0.dist-info/RECORD +69 -0
  3. libpass-1.7.5.post0.dist-info/WHEEL +4 -0
  4. libpass-1.7.5.post0.dist-info/licenses/LICENSE +116 -0
  5. passlib/__init__.py +3 -0
  6. passlib/_data/wordsets/bip39.txt +2049 -0
  7. passlib/_data/wordsets/eff_long.txt +7776 -0
  8. passlib/_data/wordsets/eff_prefixed.txt +1296 -0
  9. passlib/_data/wordsets/eff_short.txt +1296 -0
  10. passlib/_setup/__init__.py +1 -0
  11. passlib/_setup/stamp.py +159 -0
  12. passlib/apache.py +1185 -0
  13. passlib/apps.py +260 -0
  14. passlib/context.py +2066 -0
  15. passlib/crypto/__init__.py +1 -0
  16. passlib/crypto/_blowfish/__init__.py +171 -0
  17. passlib/crypto/_blowfish/_gen_files.py +256 -0
  18. passlib/crypto/_blowfish/base.py +1239 -0
  19. passlib/crypto/_blowfish/unrolled.py +1691 -0
  20. passlib/crypto/_md4.py +249 -0
  21. passlib/crypto/des.py +2283 -0
  22. passlib/crypto/digest.py +1111 -0
  23. passlib/crypto/scrypt/__init__.py +299 -0
  24. passlib/crypto/scrypt/_builtin.py +254 -0
  25. passlib/crypto/scrypt/_gen_files.py +161 -0
  26. passlib/crypto/scrypt/_salsa.py +188 -0
  27. passlib/exc.py +432 -0
  28. passlib/ext/__init__.py +1 -0
  29. passlib/ext/django/__init__.py +6 -0
  30. passlib/ext/django/models.py +38 -0
  31. passlib/ext/django/utils.py +1326 -0
  32. passlib/handlers/__init__.py +1 -0
  33. passlib/handlers/argon2.py +1119 -0
  34. passlib/handlers/bcrypt.py +1217 -0
  35. passlib/handlers/cisco.py +450 -0
  36. passlib/handlers/des_crypt.py +642 -0
  37. passlib/handlers/digests.py +184 -0
  38. passlib/handlers/django.py +545 -0
  39. passlib/handlers/fshp.py +223 -0
  40. passlib/handlers/ldap_digests.py +379 -0
  41. passlib/handlers/md5_crypt.py +375 -0
  42. passlib/handlers/misc.py +224 -0
  43. passlib/handlers/mssql.py +258 -0
  44. passlib/handlers/mysql.py +136 -0
  45. passlib/handlers/oracle.py +177 -0
  46. passlib/handlers/pbkdf2.py +521 -0
  47. passlib/handlers/phpass.py +142 -0
  48. passlib/handlers/postgres.py +61 -0
  49. passlib/handlers/roundup.py +33 -0
  50. passlib/handlers/scram.py +589 -0
  51. passlib/handlers/scrypt.py +413 -0
  52. passlib/handlers/sha1_crypt.py +173 -0
  53. passlib/handlers/sha2_crypt.py +657 -0
  54. passlib/handlers/sun_md5_crypt.py +387 -0
  55. passlib/handlers/windows.py +349 -0
  56. passlib/hash.py +111 -0
  57. passlib/hosts.py +112 -0
  58. passlib/ifc.py +354 -0
  59. passlib/pwd.py +813 -0
  60. passlib/registry.py +583 -0
  61. passlib/totp.py +1968 -0
  62. passlib/utils/__init__.py +1221 -0
  63. passlib/utils/binary.py +897 -0
  64. passlib/utils/compat/__init__.py +200 -0
  65. passlib/utils/decor.py +234 -0
  66. passlib/utils/des.py +35 -0
  67. passlib/utils/handlers.py +2857 -0
  68. passlib/utils/md4.py +34 -0
  69. passlib/utils/pbkdf2.py +188 -0
@@ -0,0 +1,897 @@
1
+ """
2
+ passlib.utils.binary - binary data encoding/decoding/manipulation
3
+ """
4
+
5
+ from base64 import (
6
+ b32decode as _b32decode,
7
+ b32encode as _b32encode,
8
+ )
9
+ from binascii import b2a_base64, a2b_base64, Error as _BinAsciiError
10
+ from passlib import exc
11
+ from passlib.utils.compat import (
12
+ bascii_to_str,
13
+ iter_byte_chars,
14
+ unicode_or_bytes,
15
+ )
16
+ from passlib.utils.decor import memoized_property
17
+
18
+ # from passlib.utils import BASE64_CHARS, HASH64_CHARS
19
+ # local
20
+ __all__ = [
21
+ # constants
22
+ "BASE64_CHARS",
23
+ "PADDED_BASE64_CHARS",
24
+ "AB64_CHARS",
25
+ "HASH64_CHARS",
26
+ "BCRYPT_CHARS",
27
+ "HEX_CHARS",
28
+ "LOWER_HEX_CHARS",
29
+ "UPPER_HEX_CHARS",
30
+ "ALL_BYTE_VALUES",
31
+ # misc
32
+ "compile_byte_translation",
33
+ # base64
34
+ "ab64_encode",
35
+ "ab64_decode",
36
+ "b64s_encode",
37
+ "b64s_decode",
38
+ # base32
39
+ "b32encode",
40
+ "b32decode",
41
+ # custom encodings
42
+ "Base64Engine",
43
+ "LazyBase64Engine",
44
+ "h64",
45
+ "h64big",
46
+ "bcrypt64",
47
+ ]
48
+
49
+ # =============================================================================
50
+ # constant strings
51
+ # =============================================================================
52
+
53
+ # -------------------------------------------------------------
54
+ # common salt_chars & checksum_chars values
55
+ # -------------------------------------------------------------
56
+
57
+ #: standard base64 charmap
58
+ BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
59
+
60
+ #: alt base64 charmap -- "." instead of "+"
61
+ AB64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./"
62
+
63
+ #: charmap used by HASH64 encoding.
64
+ HASH64_CHARS = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
65
+
66
+ #: charmap used by BCrypt
67
+ BCRYPT_CHARS = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
68
+
69
+ #: std base64 chars + padding char
70
+ PADDED_BASE64_CHARS = BASE64_CHARS + "="
71
+
72
+ #: all hex chars
73
+ HEX_CHARS = "0123456789abcdefABCDEF"
74
+
75
+ #: upper case hex chars
76
+ UPPER_HEX_CHARS = "0123456789ABCDEF"
77
+
78
+ #: lower case hex chars
79
+ LOWER_HEX_CHARS = "0123456789abcdef"
80
+
81
+ # -------------------------------------------------------------
82
+ # byte strings
83
+ # -------------------------------------------------------------
84
+
85
+ #: special byte string containing all possible byte values
86
+ #: NOTE: for efficiency, this is treated as singleton by some of the code
87
+ ALL_BYTE_VALUES = bytes(range(256))
88
+
89
+ #: some string constants we reuse
90
+ B_EMPTY = b""
91
+ B_NULL = b"\x00"
92
+ B_EQUAL = b"="
93
+
94
+ # =============================================================================
95
+ # byte translation
96
+ # =============================================================================
97
+
98
+ #: base list used to compile byte translations
99
+ _TRANSLATE_SOURCE = list(iter_byte_chars(ALL_BYTE_VALUES))
100
+
101
+
102
+ def compile_byte_translation(mapping, source=None):
103
+ """
104
+ return a 256-byte string for translating bytes using specified mapping.
105
+ bytes not specified by mapping will be left alone.
106
+
107
+ :param mapping:
108
+ dict mapping input byte (str or int) -> output byte (str or int).
109
+
110
+ :param source:
111
+ optional existing byte translation string to use as base.
112
+ (must be 255-length byte string). defaults to identity mapping.
113
+
114
+ :returns:
115
+ 255-length byte string for passing to bytes().translate.
116
+ """
117
+ if source is None:
118
+ target = _TRANSLATE_SOURCE[:]
119
+ else:
120
+ assert isinstance(source, bytes) and len(source) == 255
121
+ target = list(iter_byte_chars(source))
122
+ for k, v in mapping.items():
123
+ if isinstance(k, unicode_or_bytes):
124
+ k = ord(k)
125
+ assert isinstance(k, int) and 0 <= k < 256
126
+ if isinstance(v, str):
127
+ v = v.encode("ascii")
128
+ assert isinstance(v, bytes) and len(v) == 1
129
+ target[k] = v
130
+ return B_EMPTY.join(target)
131
+
132
+
133
+ # =============================================================================
134
+ # unpadding / stripped base64 encoding
135
+ # =============================================================================
136
+ def b64s_encode(data):
137
+ """
138
+ encode using shortened base64 format which omits padding & whitespace.
139
+ uses default ``+/`` altchars.
140
+ """
141
+ return b2a_base64(data).rstrip(_BASE64_STRIP)
142
+
143
+
144
+ def b64s_decode(data):
145
+ """
146
+ decode from shortened base64 format which omits padding & whitespace.
147
+ uses default ``+/`` altchars.
148
+ """
149
+ if isinstance(data, str):
150
+ # needs bytes for replace() call, but want to accept ascii-unicode ala a2b_base64()
151
+ try:
152
+ data = data.encode("ascii")
153
+ except UnicodeEncodeError:
154
+ raise ValueError(
155
+ "string argument should contain only ASCII characters"
156
+ ) from None
157
+ off = len(data) & 3
158
+ if off == 0:
159
+ pass
160
+ elif off == 2:
161
+ data += _BASE64_PAD2
162
+ elif off == 3:
163
+ data += _BASE64_PAD1
164
+ else: # off == 1
165
+ raise ValueError("invalid base64 input")
166
+ try:
167
+ return a2b_base64(data)
168
+ except _BinAsciiError as err:
169
+ raise TypeError(err) from None
170
+
171
+
172
+ # =============================================================================
173
+ # adapted-base64 encoding
174
+ # =============================================================================
175
+ _BASE64_STRIP = b"=\n"
176
+ _BASE64_PAD1 = b"="
177
+ _BASE64_PAD2 = b"=="
178
+
179
+ # XXX: Passlib 1.8/1.9 -- deprecate everything that's using ab64_encode(),
180
+ # have it start outputing b64s_encode() instead? can use a64_decode() to retain backwards compat.
181
+
182
+
183
+ def ab64_encode(data):
184
+ """
185
+ encode using shortened base64 format which omits padding & whitespace.
186
+ uses custom ``./`` altchars.
187
+
188
+ it is primarily used by Passlib's custom pbkdf2 hashes.
189
+ """
190
+ return b64s_encode(data).replace(b"+", b".")
191
+
192
+
193
+ def ab64_decode(data):
194
+ """
195
+ decode from shortened base64 format which omits padding & whitespace.
196
+ uses custom ``./`` altchars, but supports decoding normal ``+/`` altchars as well.
197
+
198
+ it is primarily used by Passlib's custom pbkdf2 hashes.
199
+ """
200
+ if isinstance(data, str):
201
+ # needs bytes for replace() call, but want to accept ascii-unicode ala a2b_base64()
202
+ try:
203
+ data = data.encode("ascii")
204
+ except UnicodeEncodeError:
205
+ raise ValueError(
206
+ "string argument should contain only ASCII characters"
207
+ ) from None
208
+ return b64s_decode(data.replace(b".", b"+"))
209
+
210
+
211
+ # =============================================================================
212
+ # base32 codec
213
+ # =============================================================================
214
+
215
+
216
+ def b32encode(source):
217
+ """
218
+ wrapper around :func:`base64.b32encode` which strips padding,
219
+ and returns a native string.
220
+ """
221
+ # NOTE: using upper case by default here, since 'I & L' are less
222
+ # visually ambiguous than 'i & l'
223
+ return bascii_to_str(_b32encode(source).rstrip(B_EQUAL))
224
+
225
+
226
+ #: byte translation map to replace common mistyped base32 chars.
227
+ #: XXX: could correct '1' -> 'I', but could be a mistyped lower-case 'l', so leaving it alone.
228
+ _b32_translate = compile_byte_translation({"8": "B", "0": "O"})
229
+
230
+ #: helper to add padding
231
+ _b32_decode_pad = B_EQUAL * 8
232
+
233
+
234
+ def b32decode(source):
235
+ """
236
+ wrapper around :func:`base64.b32decode`
237
+ which handles common mistyped chars.
238
+ padding optional, ignored if present.
239
+ """
240
+ # encode & correct for typos
241
+ if isinstance(source, str):
242
+ source = source.encode("ascii")
243
+ source = source.translate(_b32_translate)
244
+
245
+ # pad things so final string is multiple of 8
246
+ remainder = len(source) & 0x7
247
+ if remainder:
248
+ source += _b32_decode_pad[:-remainder]
249
+
250
+ # XXX: py27 stdlib's version of this has some inefficiencies,
251
+ # could look into using optimized version.
252
+ return _b32decode(source, True)
253
+
254
+
255
+ # =============================================================================
256
+ # base64-variant encoding
257
+ # =============================================================================
258
+
259
+
260
+ class Base64Engine(object):
261
+ """Provides routines for encoding/decoding base64 data using
262
+ arbitrary character mappings, selectable endianness, etc.
263
+
264
+ :arg charmap:
265
+ A string of 64 unique characters,
266
+ which will be used to encode successive 6-bit chunks of data.
267
+ A character's position within the string should correspond
268
+ to its 6-bit value.
269
+
270
+ :param big:
271
+ Whether the encoding should be big-endian (default False).
272
+
273
+ .. note::
274
+ This class does not currently handle base64's padding characters
275
+ in any way what so ever.
276
+
277
+ Raw Bytes <-> Encoded Bytes
278
+ ===========================
279
+ The following methods convert between raw bytes,
280
+ and strings encoded using the engine's specific base64 variant:
281
+
282
+ .. automethod:: encode_bytes
283
+ .. automethod:: decode_bytes
284
+ .. automethod:: encode_transposed_bytes
285
+ .. automethod:: decode_transposed_bytes
286
+
287
+ ..
288
+ .. automethod:: check_repair_unused
289
+ .. automethod:: repair_unused
290
+
291
+ Integers <-> Encoded Bytes
292
+ ==========================
293
+ The following methods allow encoding and decoding
294
+ unsigned integers to and from the engine's specific base64 variant.
295
+ Endianess is determined by the engine's ``big`` constructor keyword.
296
+
297
+ .. automethod:: encode_int6
298
+ .. automethod:: decode_int6
299
+
300
+ .. automethod:: encode_int12
301
+ .. automethod:: decode_int12
302
+
303
+ .. automethod:: encode_int24
304
+ .. automethod:: decode_int24
305
+
306
+ .. automethod:: encode_int64
307
+ .. automethod:: decode_int64
308
+
309
+ Informational Attributes
310
+ ========================
311
+ .. attribute:: charmap
312
+
313
+ unicode string containing list of characters used in encoding;
314
+ position in string matches 6bit value of character.
315
+
316
+ .. attribute:: bytemap
317
+
318
+ bytes version of :attr:`charmap`
319
+
320
+ .. attribute:: big
321
+
322
+ boolean flag indicating this using big-endian encoding.
323
+ """
324
+
325
+ # ===================================================================
326
+ # instance attrs
327
+ # ===================================================================
328
+ # public config
329
+ bytemap = None # charmap as bytes
330
+ big = None # little or big endian
331
+
332
+ # filled in by init based on charmap.
333
+ # (byte elem: single byte under py2, 8bit int under py3)
334
+ _encode64 = None # maps 6bit value -> byte elem
335
+ _decode64 = None # maps byte elem -> 6bit value
336
+
337
+ # helpers filled in by init based on endianness
338
+ _encode_bytes = None # throws IndexError if bad value (shouldn't happen)
339
+ _decode_bytes = None # throws KeyError if bad char.
340
+
341
+ # ===================================================================
342
+ # init
343
+ # ===================================================================
344
+ def __init__(self, charmap, big=False):
345
+ # validate charmap, generate encode64/decode64 helper functions.
346
+ if isinstance(charmap, str):
347
+ charmap = charmap.encode("latin-1")
348
+ elif not isinstance(charmap, bytes):
349
+ raise exc.ExpectedStringError(charmap, "charmap")
350
+ if len(charmap) != 64:
351
+ raise ValueError("charmap must be 64 characters in length")
352
+ if len(set(charmap)) != 64:
353
+ raise ValueError("charmap must not contain duplicate characters")
354
+ self.bytemap = charmap
355
+ self._encode64 = charmap.__getitem__
356
+ lookup = dict((value, idx) for idx, value in enumerate(charmap))
357
+ self._decode64 = lookup.__getitem__
358
+
359
+ # validate big, set appropriate helper functions.
360
+ self.big = big
361
+ if big:
362
+ self._encode_bytes = self._encode_bytes_big
363
+ self._decode_bytes = self._decode_bytes_big
364
+ else:
365
+ self._encode_bytes = self._encode_bytes_little
366
+ self._decode_bytes = self._decode_bytes_little
367
+
368
+ # TODO: support padding character
369
+ ##if padding is not None:
370
+ ## if isinstance(padding, unicode):
371
+ ## padding = padding.encode("latin-1")
372
+ ## elif not isinstance(padding, bytes):
373
+ ## raise TypeError("padding char must be unicode or bytes")
374
+ ## if len(padding) != 1:
375
+ ## raise ValueError("padding must be single character")
376
+ ##self.padding = padding
377
+
378
+ @property
379
+ def charmap(self):
380
+ """charmap as unicode"""
381
+ return self.bytemap.decode("latin-1")
382
+
383
+ # ===================================================================
384
+ # encoding byte strings
385
+ # ===================================================================
386
+ def encode_bytes(self, source):
387
+ """encode bytes to base64 string.
388
+
389
+ :arg source: byte string to encode.
390
+ :returns: byte string containing encoded data.
391
+ """
392
+ if not isinstance(source, bytes):
393
+ raise TypeError("source must be bytes, not %s" % (type(source),))
394
+ chunks, tail = divmod(len(source), 3)
395
+ next_value = iter(source).__next__
396
+ gen = self._encode_bytes(next_value, chunks, tail)
397
+ out = bytes(map(self._encode64, gen))
398
+ ##if tail:
399
+ ## padding = self.padding
400
+ ## if padding:
401
+ ## out += padding * (3-tail)
402
+ return out
403
+
404
+ def _encode_bytes_little(self, next_value, chunks, tail):
405
+ """helper used by encode_bytes() to handle little-endian encoding"""
406
+ #
407
+ # output bit layout:
408
+ #
409
+ # first byte: v1 543210
410
+ #
411
+ # second byte: v1 ....76
412
+ # +v2 3210..
413
+ #
414
+ # third byte: v2 ..7654
415
+ # +v3 10....
416
+ #
417
+ # fourth byte: v3 765432
418
+ #
419
+ idx = 0
420
+ while idx < chunks:
421
+ v1 = next_value()
422
+ v2 = next_value()
423
+ v3 = next_value()
424
+ yield v1 & 0x3F
425
+ yield ((v2 & 0x0F) << 2) | (v1 >> 6)
426
+ yield ((v3 & 0x03) << 4) | (v2 >> 4)
427
+ yield v3 >> 2
428
+ idx += 1
429
+ if tail:
430
+ v1 = next_value()
431
+ if tail == 1:
432
+ # note: 4 msb of last byte are padding
433
+ yield v1 & 0x3F
434
+ yield v1 >> 6
435
+ else:
436
+ assert tail == 2
437
+ # note: 2 msb of last byte are padding
438
+ v2 = next_value()
439
+ yield v1 & 0x3F
440
+ yield ((v2 & 0x0F) << 2) | (v1 >> 6)
441
+ yield v2 >> 4
442
+
443
+ def _encode_bytes_big(self, next_value, chunks, tail):
444
+ """helper used by encode_bytes() to handle big-endian encoding"""
445
+ #
446
+ # output bit layout:
447
+ #
448
+ # first byte: v1 765432
449
+ #
450
+ # second byte: v1 10....
451
+ # +v2 ..7654
452
+ #
453
+ # third byte: v2 3210..
454
+ # +v3 ....76
455
+ #
456
+ # fourth byte: v3 543210
457
+ #
458
+ idx = 0
459
+ while idx < chunks:
460
+ v1 = next_value()
461
+ v2 = next_value()
462
+ v3 = next_value()
463
+ yield v1 >> 2
464
+ yield ((v1 & 0x03) << 4) | (v2 >> 4)
465
+ yield ((v2 & 0x0F) << 2) | (v3 >> 6)
466
+ yield v3 & 0x3F
467
+ idx += 1
468
+ if tail:
469
+ v1 = next_value()
470
+ if tail == 1:
471
+ # note: 4 lsb of last byte are padding
472
+ yield v1 >> 2
473
+ yield (v1 & 0x03) << 4
474
+ else:
475
+ assert tail == 2
476
+ # note: 2 lsb of last byte are padding
477
+ v2 = next_value()
478
+ yield v1 >> 2
479
+ yield ((v1 & 0x03) << 4) | (v2 >> 4)
480
+ yield ((v2 & 0x0F) << 2)
481
+
482
+ # ===================================================================
483
+ # decoding byte strings
484
+ # ===================================================================
485
+
486
+ def decode_bytes(self, source):
487
+ """decode bytes from base64 string.
488
+
489
+ :arg source: byte string to decode.
490
+ :returns: byte string containing decoded data.
491
+ """
492
+ if not isinstance(source, bytes):
493
+ raise TypeError("source must be bytes, not %s" % (type(source),))
494
+ ##padding = self.padding
495
+ ##if padding:
496
+ ## # TODO: add padding size check?
497
+ ## source = source.rstrip(padding)
498
+ chunks, tail = divmod(len(source), 4)
499
+ if tail == 1:
500
+ # only 6 bits left, can't encode a whole byte!
501
+ raise ValueError("input string length cannot be == 1 mod 4")
502
+ next_value = map(self._decode64, source).__next__
503
+ try:
504
+ return bytes(self._decode_bytes(next_value, chunks, tail))
505
+ except KeyError as err:
506
+ raise ValueError("invalid character: %r" % (err.args[0],))
507
+
508
+ def _decode_bytes_little(self, next_value, chunks, tail):
509
+ """helper used by decode_bytes() to handle little-endian encoding"""
510
+ #
511
+ # input bit layout:
512
+ #
513
+ # first byte: v1 ..543210
514
+ # +v2 10......
515
+ #
516
+ # second byte: v2 ....5432
517
+ # +v3 3210....
518
+ #
519
+ # third byte: v3 ......54
520
+ # +v4 543210..
521
+ #
522
+ idx = 0
523
+ while idx < chunks:
524
+ v1 = next_value()
525
+ v2 = next_value()
526
+ v3 = next_value()
527
+ v4 = next_value()
528
+ yield v1 | ((v2 & 0x3) << 6)
529
+ yield (v2 >> 2) | ((v3 & 0xF) << 4)
530
+ yield (v3 >> 4) | (v4 << 2)
531
+ idx += 1
532
+ if tail:
533
+ # tail is 2 or 3
534
+ v1 = next_value()
535
+ v2 = next_value()
536
+ yield v1 | ((v2 & 0x3) << 6)
537
+ # NOTE: if tail == 2, 4 msb of v2 are ignored (should be 0)
538
+ if tail == 3:
539
+ # NOTE: 2 msb of v3 are ignored (should be 0)
540
+ v3 = next_value()
541
+ yield (v2 >> 2) | ((v3 & 0xF) << 4)
542
+
543
+ def _decode_bytes_big(self, next_value, chunks, tail):
544
+ """helper used by decode_bytes() to handle big-endian encoding"""
545
+ #
546
+ # input bit layout:
547
+ #
548
+ # first byte: v1 543210..
549
+ # +v2 ......54
550
+ #
551
+ # second byte: v2 3210....
552
+ # +v3 ....5432
553
+ #
554
+ # third byte: v3 10......
555
+ # +v4 ..543210
556
+ #
557
+ idx = 0
558
+ while idx < chunks:
559
+ v1 = next_value()
560
+ v2 = next_value()
561
+ v3 = next_value()
562
+ v4 = next_value()
563
+ yield (v1 << 2) | (v2 >> 4)
564
+ yield ((v2 & 0xF) << 4) | (v3 >> 2)
565
+ yield ((v3 & 0x3) << 6) | v4
566
+ idx += 1
567
+ if tail:
568
+ # tail is 2 or 3
569
+ v1 = next_value()
570
+ v2 = next_value()
571
+ yield (v1 << 2) | (v2 >> 4)
572
+ # NOTE: if tail == 2, 4 lsb of v2 are ignored (should be 0)
573
+ if tail == 3:
574
+ # NOTE: 2 lsb of v3 are ignored (should be 0)
575
+ v3 = next_value()
576
+ yield ((v2 & 0xF) << 4) | (v3 >> 2)
577
+
578
+ # ===================================================================
579
+ # encode/decode helpers
580
+ # ===================================================================
581
+
582
+ # padmap2/3 - dict mapping last char of string ->
583
+ # equivalent char with no padding bits set.
584
+
585
+ def __make_padset(self, bits):
586
+ """helper to generate set of valid last chars & bytes"""
587
+ pset = set(c for i, c in enumerate(self.bytemap) if not i & bits)
588
+ pset.update(c for i, c in enumerate(self.charmap) if not i & bits)
589
+ return frozenset(pset)
590
+
591
+ @memoized_property
592
+ def _padinfo2(self):
593
+ """mask to clear padding bits, and valid last bytes (for strings 2 % 4)"""
594
+ # 4 bits of last char unused (lsb for big, msb for little)
595
+ bits = 15 if self.big else (15 << 2)
596
+ return ~bits, self.__make_padset(bits)
597
+
598
+ @memoized_property
599
+ def _padinfo3(self):
600
+ """mask to clear padding bits, and valid last bytes (for strings 3 % 4)"""
601
+ # 2 bits of last char unused (lsb for big, msb for little)
602
+ bits = 3 if self.big else (3 << 4)
603
+ return ~bits, self.__make_padset(bits)
604
+
605
+ def check_repair_unused(self, source):
606
+ """helper to detect & clear invalid unused bits in last character.
607
+
608
+ :arg source:
609
+ encoded data (as ascii bytes or unicode).
610
+
611
+ :returns:
612
+ `(True, result)` if the string was repaired,
613
+ `(False, source)` if the string was ok as-is.
614
+ """
615
+ # figure out how many padding bits there are in last char.
616
+ tail = len(source) & 3
617
+ if tail == 2:
618
+ mask, padset = self._padinfo2
619
+ elif tail == 3:
620
+ mask, padset = self._padinfo3
621
+ elif not tail:
622
+ return False, source
623
+ else:
624
+ raise ValueError("source length must != 1 mod 4")
625
+
626
+ # check if last char is ok (padset contains bytes & unicode versions)
627
+ last = source[-1]
628
+ if last in padset:
629
+ return False, source
630
+
631
+ # we have dirty bits - repair the string by decoding last char,
632
+ # clearing the padding bits via <mask>, and encoding new char.
633
+ if isinstance(source, str):
634
+ cm = self.charmap
635
+ last = cm[cm.index(last) & mask]
636
+ assert last in padset, "failed to generate valid padding char"
637
+ else:
638
+ # NOTE: this assumes ascii-compat encoding, and that
639
+ # all chars used by encoding are 7-bit ascii.
640
+ last = self._encode64(self._decode64(last) & mask)
641
+ assert last in padset, "failed to generate valid padding char"
642
+ last = bytes([last])
643
+ return True, source[:-1] + last
644
+
645
+ def repair_unused(self, source):
646
+ return self.check_repair_unused(source)[1]
647
+
648
+ ##def transcode(self, source, other):
649
+ ## return ''.join(
650
+ ## other.charmap[self.charmap.index(char)]
651
+ ## for char in source
652
+ ## )
653
+
654
+ ##def random_encoded_bytes(self, size, random=None, unicode=False):
655
+ ## "return random encoded string of given size"
656
+ ## data = getrandstr(random or rng,
657
+ ## self.charmap if unicode else self.bytemap, size)
658
+ ## return self.repair_unused(data)
659
+
660
+ # ===================================================================
661
+ # transposed encoding/decoding
662
+ # ===================================================================
663
+ def encode_transposed_bytes(self, source, offsets):
664
+ """encode byte string, first transposing source using offset list"""
665
+ if not isinstance(source, bytes):
666
+ raise TypeError("source must be bytes, not %s" % (type(source),))
667
+ tmp = bytes(source[off] for off in offsets)
668
+ return self.encode_bytes(tmp)
669
+
670
+ def decode_transposed_bytes(self, source, offsets):
671
+ """decode byte string, then reverse transposition described by offset list"""
672
+ # NOTE: if transposition does not use all bytes of source,
673
+ # the original can't be recovered... and bytes() will throw
674
+ # an error because 1+ values in <buf> will be None.
675
+ tmp = self.decode_bytes(source)
676
+ buf = [None] * len(offsets)
677
+ for off, char in zip(offsets, tmp):
678
+ buf[off] = char
679
+ return bytes(buf)
680
+
681
+ # ===================================================================
682
+ # integer decoding helpers - mainly used by des_crypt family
683
+ # ===================================================================
684
+ def _decode_int(self, source, bits):
685
+ """decode base64 string -> integer
686
+
687
+ :arg source: base64 string to decode.
688
+ :arg bits: number of bits in resulting integer.
689
+
690
+ :raises ValueError:
691
+ * if the string contains invalid base64 characters.
692
+ * if the string is not long enough - it must be at least
693
+ ``int(ceil(bits/6))`` in length.
694
+
695
+ :returns:
696
+ a integer in the range ``0 <= n < 2**bits``
697
+ """
698
+ if not isinstance(source, bytes):
699
+ raise TypeError("source must be bytes, not %s" % (type(source),))
700
+ big = self.big
701
+ pad = -bits % 6
702
+ chars = (bits + pad) / 6
703
+ if len(source) != chars:
704
+ raise ValueError("source must be %d chars" % (chars,))
705
+ decode = self._decode64
706
+ out = 0
707
+ try:
708
+ for c in source if big else reversed(source):
709
+ out = (out << 6) + decode(c)
710
+ except KeyError:
711
+ raise ValueError("invalid character in string: %r" % (c,))
712
+ if pad:
713
+ # strip padding bits
714
+ if big:
715
+ out >>= pad
716
+ else:
717
+ out &= (1 << bits) - 1
718
+ return out
719
+
720
+ # ---------------------------------------------------------------
721
+ # optimized versions for common integer sizes
722
+ # ---------------------------------------------------------------
723
+
724
+ def decode_int6(self, source):
725
+ """decode single character -> 6 bit integer"""
726
+ if not isinstance(source, bytes):
727
+ raise TypeError("source must be bytes, not %s" % (type(source),))
728
+ if len(source) != 1:
729
+ raise ValueError("source must be exactly 1 byte")
730
+ # convert to 8bit int before doing lookup
731
+ source = source[0]
732
+ try:
733
+ return self._decode64(source)
734
+ except KeyError:
735
+ raise ValueError("invalid character")
736
+
737
+ def decode_int12(self, source):
738
+ """decodes 2 char string -> 12-bit integer"""
739
+ if not isinstance(source, bytes):
740
+ raise TypeError("source must be bytes, not %s" % (type(source),))
741
+ if len(source) != 2:
742
+ raise ValueError("source must be exactly 2 bytes")
743
+ decode = self._decode64
744
+ try:
745
+ if self.big:
746
+ return decode(source[1]) + (decode(source[0]) << 6)
747
+ else:
748
+ return decode(source[0]) + (decode(source[1]) << 6)
749
+ except KeyError:
750
+ raise ValueError("invalid character")
751
+
752
+ def decode_int24(self, source):
753
+ """decodes 4 char string -> 24-bit integer"""
754
+ if not isinstance(source, bytes):
755
+ raise TypeError("source must be bytes, not %s" % (type(source),))
756
+ if len(source) != 4:
757
+ raise ValueError("source must be exactly 4 bytes")
758
+ decode = self._decode64
759
+ try:
760
+ if self.big:
761
+ return (
762
+ decode(source[3])
763
+ + (decode(source[2]) << 6)
764
+ + (decode(source[1]) << 12)
765
+ + (decode(source[0]) << 18)
766
+ )
767
+ else:
768
+ return (
769
+ decode(source[0])
770
+ + (decode(source[1]) << 6)
771
+ + (decode(source[2]) << 12)
772
+ + (decode(source[3]) << 18)
773
+ )
774
+ except KeyError:
775
+ raise ValueError("invalid character")
776
+
777
+ def decode_int30(self, source):
778
+ """decode 5 char string -> 30 bit integer"""
779
+ return self._decode_int(source, 30)
780
+
781
+ def decode_int64(self, source):
782
+ """decode 11 char base64 string -> 64-bit integer
783
+
784
+ this format is used primarily by des-crypt & variants to encode
785
+ the DES output value used as a checksum.
786
+ """
787
+ return self._decode_int(source, 64)
788
+
789
+ # ===================================================================
790
+ # integer encoding helpers - mainly used by des_crypt family
791
+ # ===================================================================
792
+ def _encode_int(self, value, bits):
793
+ """encode integer into base64 format
794
+
795
+ :arg value: non-negative integer to encode
796
+ :arg bits: number of bits to encode
797
+
798
+ :returns:
799
+ a string of length ``int(ceil(bits/6.0))``.
800
+ """
801
+ assert value >= 0, "caller did not sanitize input"
802
+ pad = -bits % 6
803
+ bits += pad
804
+ if self.big:
805
+ itr = range(bits - 6, -6, -6)
806
+ # shift to add lsb padding.
807
+ value <<= pad
808
+ else:
809
+ itr = range(0, bits, 6)
810
+ # padding is msb, so no change needed.
811
+ return bytes(map(self._encode64, ((value >> off) & 0x3F for off in itr)))
812
+
813
+ # ---------------------------------------------------------------
814
+ # optimized versions for common integer sizes
815
+ # ---------------------------------------------------------------
816
+
817
+ def encode_int6(self, value):
818
+ """encodes 6-bit integer -> single hash64 character"""
819
+ if value < 0 or value > 63:
820
+ raise ValueError("value out of range")
821
+ return self.bytemap[value : value + 1]
822
+
823
+ def encode_int12(self, value):
824
+ """encodes 12-bit integer -> 2 char string"""
825
+ if value < 0 or value > 0xFFF:
826
+ raise ValueError("value out of range")
827
+ raw = [value & 0x3F, (value >> 6) & 0x3F]
828
+ if self.big:
829
+ raw = reversed(raw)
830
+ return bytes(map(self._encode64, raw))
831
+
832
+ def encode_int24(self, value):
833
+ """encodes 24-bit integer -> 4 char string"""
834
+ if value < 0 or value > 0xFFFFFF:
835
+ raise ValueError("value out of range")
836
+ raw = [
837
+ value & 0x3F,
838
+ (value >> 6) & 0x3F,
839
+ (value >> 12) & 0x3F,
840
+ (value >> 18) & 0x3F,
841
+ ]
842
+ if self.big:
843
+ raw = reversed(raw)
844
+ return bytes(map(self._encode64, raw))
845
+
846
+ def encode_int30(self, value):
847
+ """decode 5 char string -> 30 bit integer"""
848
+ if value < 0 or value > 0x3FFFFFFF:
849
+ raise ValueError("value out of range")
850
+ return self._encode_int(value, 30)
851
+
852
+ def encode_int64(self, value):
853
+ """encode 64-bit integer -> 11 char hash64 string
854
+
855
+ this format is used primarily by des-crypt & variants to encode
856
+ the DES output value used as a checksum.
857
+ """
858
+ if value < 0 or value > 0xFFFFFFFFFFFFFFFF:
859
+ raise ValueError("value out of range")
860
+ return self._encode_int(value, 64)
861
+
862
+ # ===================================================================
863
+ # eof
864
+ # ===================================================================
865
+
866
+
867
+ class LazyBase64Engine(Base64Engine):
868
+ """Base64Engine which delays initialization until it's accessed"""
869
+
870
+ _lazy_opts = None
871
+
872
+ def __init__(self, *args, **kwds):
873
+ self._lazy_opts = (args, kwds)
874
+
875
+ def _lazy_init(self):
876
+ args, kwds = self._lazy_opts
877
+ super().__init__(*args, **kwds)
878
+ del self._lazy_opts
879
+ self.__class__ = Base64Engine
880
+
881
+ def __getattribute__(self, attr):
882
+ if not attr.startswith("_"):
883
+ self._lazy_init()
884
+ return object.__getattribute__(self, attr)
885
+
886
+
887
+ # -------------------------------------------------------------
888
+ # common variants
889
+ # -------------------------------------------------------------
890
+
891
+ h64 = LazyBase64Engine(HASH64_CHARS)
892
+ h64big = LazyBase64Engine(HASH64_CHARS, big=True)
893
+ bcrypt64 = LazyBase64Engine(BCRYPT_CHARS, big=True)
894
+
895
+ # =============================================================================
896
+ # eof
897
+ # =============================================================================