diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2016-11-28 13:05:30 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2016-11-28 13:05:30 -0500 |
| commit | 2b4b86a81a5b9845a92fab89e804d428a3d6da99 (patch) | |
| tree | f79b2dedd8e943e4f1f14d418e110a0f8892ffed | |
| parent | 59a6a2bdc1ff24abacdca74967ebd75a23aa9fc2 (diff) | |
| download | passlib-2b4b86a81a5b9845a92fab89e804d428a3d6da99.tar.gz | |
general: went ahead and removed a bunch of deprecated features that were scheduled
for removal in v1.8.
this removes CryptPolicy, unix_fallback, some old HtpasswdFile methods,
and more. tests were updated as well. see history/1.8 for a complete list.
29 files changed, 127 insertions, 1959 deletions
diff --git a/admin/benchmarks.py b/admin/benchmarks.py index fb02b39..f664cea 100644 --- a/admin/benchmarks.py +++ b/admin/benchmarks.py @@ -90,10 +90,6 @@ class benchmark: sample_config_1p = os.path.join(root, "passlib", "tests", "sample_config_1s.cfg") from passlib.context import CryptContext -if hasattr(CryptContext, "from_path"): - CryptPolicy = None -else: - from passlib.context import CryptPolicy class BlankHandler(uh.HasRounds, uh.HasSalt, uh.GenericHandler): name = "blank" @@ -133,12 +129,8 @@ OTHER = u("setecastronomy") def test_context_from_path(): """test speed of CryptContext.from_path()""" path = sample_config_1p - if CryptPolicy: - def helper(): - CryptPolicy.from_path(path) - else: - def helper(): - CryptContext.from_path(path) + def helper(): + CryptContext.from_path(path) return helper @benchmark.constructor() @@ -150,14 +142,9 @@ def test_context_update(): deprecated = [ "des_crypt" ], sha512_crypt__min_rounds=4000, ) - if CryptPolicy: - policy=CryptPolicy.from_path(sample_config_1p) - def helper(): - policy.replace(**kwds) - else: - ctx = CryptContext.from_path(sample_config_1p) - def helper(): - ctx.copy(**kwds) + ctx = CryptContext.from_path(sample_config_1p) + def helper(): + ctx.copy(**kwds) return helper @benchmark.constructor() diff --git a/docs/history/1.6.rst b/docs/history/1.6.rst index 1406b5f..466343f 100644 --- a/docs/history/1.6.rst +++ b/docs/history/1.6.rst @@ -280,7 +280,7 @@ CryptContext * All new (and hopefully clearer) :ref:`tutorial <context-tutorial>` and :ref:`reference <context-reference>` documentation. - * The :class:`CryptPolicy` class and the :attr:`!CryptContext.policy` attribute have been deprecated. + * The :class:`!CryptPolicy` class and the :attr:`!CryptContext.policy` attribute have been deprecated. This was a semi-internal class, which most applications were not involved with at all, but to be conservative about @@ -303,7 +303,7 @@ CryptContext can now be set to the special string ``"auto"``; which will automatically deprecate all schemes except for the default one. - * The :ref:`min_verify_time <context-min-verify-time-option>` keyword + * The ``min_verify_time`` keyword has been deprecated, will be ignored in release 1.7, and will be removed in release 1.8. It was never very useful, and now complicates the internal code needlessly. diff --git a/docs/history/1.7.rst b/docs/history/1.7.rst index 0eebf14..27ab820 100644 --- a/docs/history/1.7.rst +++ b/docs/history/1.7.rst @@ -292,7 +292,7 @@ Changes in existing behavior: Scheduled removal of features: - * **[minor]** :mod:`passlib.context`: The :ref:`min_verify_time <context-min-verify-time-option>` keyword + * **[minor]** :mod:`passlib.context`: The ``min_verify_time`` keyword that was deprecated in release 1.6, is now completely ignored. Support will be removed entirely in release 1.8. See the new :ref:`harden_verify <context-harden-verify-option>` keyword diff --git a/docs/history/1.8.rst b/docs/history/1.8.rst index d540863..6d518fb 100644 --- a/docs/history/1.8.rst +++ b/docs/history/1.8.rst @@ -4,7 +4,78 @@ Passlib 1.8 =========== +.. rst-class:: emphasize-children toc-always-open + **1.8.0** (NOT YET RELEASED) ============================ -* 1.8 is under development, and tenatively scheduled for release in late 2017
\ No newline at end of file +Overview +-------- + +.. rst-class:: without-title + +.. warning:: + + **1.8 is under development,** and tenatively scheduled for release in late 2017. + + See https://passlib.readthedocs.io/en/stable/history/1.7.html for the latest release. + +Backwards Incompatibilities +--------------------------- +The following previously-deprecated features were removed, +though few of these should be in use, as they've been deprecated +for a number of years / releases: + + **passlib.apache:** + + .. py:currentmodule:: passlib.apache + + * :mod:`passlib.apache`: A number of deprecated options & methods were removed from + :class:`HtpasswdFile` and :class:`Htdigest`: + + - Support for setting ``encoding=None`` removed, use ``return_unicode=True`` instead. + - ``autoload=False`` keyword removed, use ``new=True`` instead. + - :meth:`!load` method no longer supports ``force=False``, use :meth:`~HtpasswdFile.load_if_changed` instead. + - :meth:`!update` alias removed, use :meth:`~HtpasswdFile.set_password` instead. + - :meth:`!find` alias removed, use :meth:`~HtpasswdFile.get_hash` instead. + - :meth:`!verify` alias removed, use :meth:`~HtpasswdFile.check_password` instead. + - ``default`` keyword removed, use ``default_scheme`` instead. + + **passlib.context:** + + .. py:currentmodule:: passlib.context + + * The :class:`!passlib.context.CryptPolicy` class was removed. + Code should be using the equivalent :meth:`~CryptContext` methods instead. + + * Concurrent with that, :class:`CryptContext`'s ``policy`` keyword and attribute + were removed, along with :class:`LazyCryptContext`'s ``create_policy`` keyword. + + * :meth:`!CryptContext.replace` alias removed, use :meth:`CryptContext.using` instead. + + * :class:`CryptContext`'s ``min_verify_time`` keyword removed, use ``harden_verify=True`` instead. + + **passlib.hash:** + + .. py:currentmodule:: passlib.hash + + * :class:`!passlib.hash.unix_fallback` was removed, use :class:`~unix_disabled` instead. + + **other modules:** + + * In :mod:`passlib.ext.django`, support for ``CONFIG=None`` was dropped. + + * The deprecated :mod:`!passlib.win32` module was removed, use :class:`passlib.hash.lmhash` hash instead. + + **internal details:** + + .. py:currentmodule:: passlib.hash + + * The :meth:`!passlib.hash.nthash.raw_nthash` alias was removed, use :meth:`nthash.raw` instead. + + * In :mod:`passlib.utils.handlers`: :class:`!StaticHandler` subclasses must now always implement + :meth:`!_calc_checksum`, the old genhash-based style is no longer supported or checked for. + + * The deprecated :func:`passlib.utils.des.mdes_encrypt_int_block` method was removed. + + * The :func:`passlib.utils.pbkdf2.norm_hash_name` alias was removed, use :func:`passlib.crypto.digest.norm_hash_name` instead. diff --git a/docs/lib/passlib.apache.rst b/docs/lib/passlib.apache.rst index 6274159..4e81b09 100644 --- a/docs/lib/passlib.apache.rst +++ b/docs/lib/passlib.apache.rst @@ -19,6 +19,10 @@ htpasswd and htdigest files; though the use of two helper classes. These classes will now preserve blank lines & "#" comments when updating htpasswd files; previous releases would throw a parse error. +.. versionchanged:: 1.8 + + A number of methods deprecated since 1.6, have been removed. + .. index:: Apache; htpasswd Htpasswd Files diff --git a/docs/lib/passlib.context.rst b/docs/lib/passlib.context.rst index b2f7248..b1b6a86 100644 --- a/docs/lib/passlib.context.rst +++ b/docs/lib/passlib.context.rst @@ -166,24 +166,6 @@ Options which directly affect the behavior of the CryptContext instance: .. versionadded:: 1.7 -.. _context-min-verify-time-option: - -``min_verify_time`` - - If specified, unsuccessful :meth:`~CryptContext.verify` - calls will be penalized, and take at least this may - seconds before the method returns. May be an integer - or fractional number of seconds. - - .. deprecated:: 1.6 - This option has not proved very useful, is ignored by 1.7, - and will be removed in version 1.8. - - .. versionchanged:: 1.7 - Per deprecation roadmap above, this option is now ignored. - - See ``harden_verify`` below for a replacement. - .. _context-harden-verify-option: ``harden_verify`` @@ -553,9 +535,3 @@ if any invalid-but-correctable values are encountered Other Helpers ============= .. autoclass:: LazyCryptContext([schemes=None,] \*\*kwds [, onload=None]) - -.. rst-class:: html-toggle - -The CryptPolicy Class (deprecated) -================================== -.. autoclass:: CryptPolicy diff --git a/docs/lib/passlib.hash.unix_disabled.rst b/docs/lib/passlib.hash.unix_disabled.rst index 8bdf9c3..2c68144 100644 --- a/docs/lib/passlib.hash.unix_disabled.rst +++ b/docs/lib/passlib.hash.unix_disabled.rst @@ -36,10 +36,6 @@ Interface ========= .. autoclass:: unix_disabled() -Deprecated Interface -==================== -.. autoclass:: unix_fallback() - Deviations ========== According to the Linux ``shadow`` man page, an empty string is treated diff --git a/docs/lib/passlib.utils.pbkdf2.rst b/docs/lib/passlib.utils.pbkdf2.rst index cfc503a..a72628a 100644 --- a/docs/lib/passlib.utils.pbkdf2.rst +++ b/docs/lib/passlib.utils.pbkdf2.rst @@ -32,6 +32,4 @@ PKCS#5 Key Derivation Functions Helper Functions ================ -.. autofunction:: norm_hash_name - .. autofunction:: get_prf diff --git a/passlib/apache.py b/passlib/apache.py index af1fb8b..cbf3ed9 100644 --- a/passlib/apache.py +++ b/passlib/apache.py @@ -107,17 +107,14 @@ class _CommonFile(object): #=================================================================== # init #=================================================================== - def __init__(self, path=None, new=False, autoload=True, autosave=False, + # XXX: add a new() classmethod, ala TOTP.new()? + + def __init__(self, path=None, new=False, autosave=False, encoding="utf-8", return_unicode=PY3, ): # set encoding if not encoding: - warn("``encoding=None`` is deprecated as of Passlib 1.6, " - "and will cause a ValueError in Passlib 1.8, " - "use ``return_unicode=False`` instead.", - DeprecationWarning, stacklevel=2) - encoding = "utf-8" - return_unicode = False + raise TypeError("'encoding' is required") elif not is_ascii_codec(encoding): # htpasswd/htdigest files assumes 1-byte chars, and use ":" separator, # so only ascii-compatible encodings are allowed. @@ -131,11 +128,6 @@ class _CommonFile(object): self._mtime = 0 # init db - if not autoload: - warn("``autoload=False`` is deprecated as of Passlib 1.6, " - "and will be removed in Passlib 1.8, use ``new=True`` instead", - DeprecationWarning, stacklevel=2) - new = True if path and not new: self.load() else: @@ -181,33 +173,17 @@ class _CommonFile(object): self.load() return True - def load(self, path=None, force=True): + def load(self, path=None): """Load state from local file. If no path is specified, attempts to load from ``self.path``. :type path: str :arg path: local file to load from - - :type force: bool - :param force: - if ``force=False``, only load from ``self.path`` if file - has changed since last load. - - .. deprecated:: 1.6 - This keyword will be removed in Passlib 1.8; - Applications should use :meth:`load_if_changed` instead. """ if path is not None: with open(path, "rb") as fh: self._mtime = 0 self._load_lines(fh) - elif not force: - warn("%(name)s.load(force=False) is deprecated as of Passlib 1.6," - "and will be removed in Passlib 1.8; " - "use %(name)s.load_if_changed() instead." % - dict(name=self.__class__.__name__), - DeprecationWarning, stacklevel=2) - return self.load_if_changed() elif self._path: with open(self._path, "rb") as fh: self._mtime = os.path.getmtime(self._path) @@ -554,7 +530,7 @@ class HtpasswdFile(_CommonFile): .. versionadded:: 1.6 This feature was previously enabled by setting ``autoload=False``. - That alias has been deprecated, and will be removed in Passlib 1.8 + That alias was removed in Passlib 1.8 :type autosave: bool :param autosave: @@ -606,7 +582,7 @@ class HtpasswdFile(_CommonFile): .. versionadded:: 1.6 This keyword was previously named ``default``. That alias - has been deprecated, and will be removed in Passlib 1.8. + was removed in Passlib 1.8. .. versionchanged:: 1.6.3 @@ -632,23 +608,6 @@ class HtpasswdFile(_CommonFile): will probably not be usable by another application, and particularly not by Apache. - :param autoload: - Set to ``False`` to prevent the constructor from automatically - loaded the file from disk. - - .. deprecated:: 1.6 - This has been replaced by the *new* keyword. - Instead of setting ``autoload=False``, you should use - ``new=True``. Support for this keyword will be removed - in Passlib 1.8. - - :param default: - Change the default algorithm used to hash new passwords. - - .. deprecated:: 1.6 - This has been renamed to *default_scheme* for clarity. - Support for this alias will be removed in Passlib 1.8. - Loading & Saving ================ .. automethod:: load @@ -704,12 +663,6 @@ class HtpasswdFile(_CommonFile): #=================================================================== def __init__(self, path=None, default_scheme=None, context=htpasswd_context, **kwds): - if 'default' in kwds: - warn("``default`` is deprecated as of Passlib 1.6, " - "and will be removed in Passlib 1.8, it has been renamed " - "to ``default_scheem``.", - DeprecationWarning, stacklevel=2) - default_scheme = kwds.pop("default") if default_scheme: if default_scheme in _warn_no_bcrypt: warn("HtpasswdFile: no bcrypt backends available, " @@ -763,24 +716,17 @@ class HtpasswdFile(_CommonFile): .. versionchanged:: 1.6 This method was previously called ``update``, it was renamed to prevent ambiguity with the dictionary method. - The old alias is deprecated, and will be removed in Passlib 1.8. + The old alias was removed in Passlib 1.8. """ hash = self.context.hash(password) return self.set_hash(user, hash) - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="set_password") - def update(self, user, password): - """set password for user""" - return self.set_password(user, password) - def get_hash(self, user): """Return hash stored for user, or ``None`` if user not found. .. versionchanged:: 1.6 This method was previously named ``find``, it was renamed - for clarity. The old name is deprecated, and will be removed - in Passlib 1.8. + for clarity. The old name was removed in Passlib 1.8. """ try: return self._records[self._encode_user(user)] @@ -805,12 +751,6 @@ class HtpasswdFile(_CommonFile): self._autosave() return existing - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="get_hash") - def find(self, user): - """return hash for user""" - return self.get_hash(user) - # XXX: rename to something more explicit, like delete_user()? def delete(self, user): """Delete user's entry. @@ -839,7 +779,7 @@ class HtpasswdFile(_CommonFile): .. versionchanged:: 1.6 This method was previously called ``verify``, it was renamed to prevent ambiguity with the :class:`!CryptContext` method. - The old alias is deprecated, and will be removed in Passlib 1.8. + The old alias was removed in Passlib 1.8. """ user = self._encode_user(user) hash = self._records.get(user) @@ -857,12 +797,6 @@ class HtpasswdFile(_CommonFile): self._autosave() return ok - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="check_password") - def verify(self, user, password): - """verify password for user""" - return self.check_password(user, password) - #=================================================================== # eoc #=================================================================== @@ -919,7 +853,7 @@ class HtdigestFile(_CommonFile): .. versionadded:: 1.6 This feature was previously enabled by setting ``autoload=False``. - That alias has been deprecated, and will be removed in Passlib 1.8 + That alias was removed in Passlib 1.8 :type autosave: bool :param autosave: @@ -940,16 +874,6 @@ class HtdigestFile(_CommonFile): This is also exposed as a readonly instance attribute. - :param autoload: - Set to ``False`` to prevent the constructor from automatically - loaded the file from disk. - - .. deprecated:: 1.6 - This has been replaced by the *new* keyword. - Instead of setting ``autoload=False``, you should use - ``new=True``. Support for this keyword will be removed - in Passlib 1.8. - Loading & Saving ================ .. automethod:: load @@ -1112,12 +1036,6 @@ class HtdigestFile(_CommonFile): hash = htdigest.hash(password, user, realm, encoding=self.encoding) return self.set_hash(user, realm, hash) - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="set_password") - def update(self, user, realm, password): - """set password for user""" - return self.set_password(user, realm, password) - def get_hash(self, user, realm=None): """Return :class:`~passlib.hash.htdigest` hash stored for user. @@ -1126,8 +1044,7 @@ class HtdigestFile(_CommonFile): .. versionchanged:: 1.6 This method was previously named ``find``, it was renamed - for clarity. The old name is deprecated, and will be removed - in Passlib 1.8. + for clarity. The old name is was removed Passlib 1.8. """ key = self._encode_key(user, realm) hash = self._records.get(key) @@ -1163,12 +1080,6 @@ class HtdigestFile(_CommonFile): self._autosave() return existing - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="get_hash") - def find(self, user, realm): - """return hash for user""" - return self.get_hash(user, realm) - # XXX: rename to something more explicit, like delete_user()? def delete(self, user, realm=None): """Delete user's entry for specified realm. @@ -1218,7 +1129,7 @@ class HtdigestFile(_CommonFile): .. versionchanged:: 1.6 This method was previously called ``verify``, it was renamed to prevent ambiguity with the :class:`!CryptContext` method. - The old alias is deprecated, and will be removed in Passlib 1.8. + The old alias was removed in Passlib 1.8. """ if password is _UNSET: # called w/ two args - (user, password), use default realm @@ -1231,12 +1142,6 @@ class HtdigestFile(_CommonFile): return htdigest.verify(password, hash, user, realm, encoding=self.encoding) - @deprecated_method(deprecated="1.6", removed="1.8", - replacement="check_password") - def verify(self, user, realm, password): - """verify password for user""" - return self.check_password(user, realm, password) - #=================================================================== # eoc #=================================================================== diff --git a/passlib/apps.py b/passlib/apps.py index 7c4be06..9217d40 100644 --- a/passlib/apps.py +++ b/passlib/apps.py @@ -56,7 +56,6 @@ def _load_master_config(): # disabled handlers 'django_disabled', 'unix_disabled', - 'unix_fallback', ] for name in excluded: schemes.remove(name) diff --git a/passlib/context.py b/passlib/context.py index 433a9d0..e5afe7b 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -2,8 +2,8 @@ #============================================================================= # imports #============================================================================= -from __future__ import with_statement # core +from __future__ import absolute_import, division, print_function import re import logging; log = logging.getLogger(__name__) import threading @@ -28,7 +28,6 @@ from passlib.utils.decor import deprecated_method, memoized_property __all__ = [ 'CryptContext', 'LazyCryptContext', - 'CryptPolicy', ] #============================================================================= @@ -79,512 +78,6 @@ def _always_needs_update(hash, secret=None): _global_settings = set(["truncate_error", "vary_rounds"]) #============================================================================= -# crypt policy -#============================================================================= -_preamble = ("The CryptPolicy class has been deprecated as of " - "Passlib 1.6, and will be removed in Passlib 1.8. ") - -class CryptPolicy(object): - """ - .. deprecated:: 1.6 - This class has been deprecated, and will be removed in Passlib 1.8. - All of its functionality has been rolled into :class:`CryptContext`. - - This class previously stored the configuration options for the - CryptContext class. In the interest of interface simplification, - all of this class' functionality has been rolled into the CryptContext - class itself. - The documentation for this class is now focused on documenting how to - migrate to the new api. Additionally, where possible, the deprecation - warnings issued by the CryptPolicy methods will list the replacement call - that should be used. - - Constructors - ============ - CryptPolicy objects can be constructed directly using any of - the keywords accepted by :class:`CryptContext`. Direct uses of the - :class:`!CryptPolicy` constructor should either pass the keywords - directly into the CryptContext constructor, or to :meth:`CryptContext.update` - if the policy object was being used to update an existing context object. - - In addition to passing in keywords directly, - CryptPolicy objects can be constructed by the following methods: - - .. automethod:: from_path - .. automethod:: from_string - .. automethod:: from_source - .. automethod:: from_sources - .. automethod:: replace - - Introspection - ============= - All of the informational methods provided by this class have been deprecated - by identical or similar methods in the :class:`CryptContext` class: - - .. automethod:: has_schemes - .. automethod:: schemes - .. automethod:: iter_handlers - .. automethod:: get_handler - .. automethod:: get_options - .. automethod:: handler_is_deprecated - .. automethod:: get_min_verify_time - - Exporting - ========= - .. automethod:: iter_config - .. automethod:: to_dict - .. automethod:: to_file - .. automethod:: to_string - - .. note:: - CryptPolicy are immutable. - Use the :meth:`replace` method to mutate existing instances. - - .. deprecated:: 1.6 - """ - #=================================================================== - # class methods - #=================================================================== - @classmethod - def from_path(cls, path, section="passlib", encoding="utf-8"): - """create a CryptPolicy instance from a local file. - - .. deprecated:: 1.6 - - Creating a new CryptContext from a file, which was previously done via - ``CryptContext(policy=CryptPolicy.from_path(path))``, can now be - done via ``CryptContext.from_path(path)``. - See :meth:`CryptContext.from_path` for details. - - Updating an existing CryptContext from a file, which was previously done - ``context.policy = CryptPolicy.from_path(path)``, can now be - done via ``context.load_path(path)``. - See :meth:`CryptContext.load_path` for details. - """ - warn(_preamble + - "Instead of ``CryptPolicy.from_path(path)``, " - "use ``CryptContext.from_path(path)`` " - " or ``context.load_path(path)`` for an existing CryptContext.", - DeprecationWarning, stacklevel=2) - return cls(_internal_context=CryptContext.from_path(path, section, - encoding)) - - @classmethod - def from_string(cls, source, section="passlib", encoding="utf-8"): - """create a CryptPolicy instance from a string. - - .. deprecated:: 1.6 - - Creating a new CryptContext from a string, which was previously done via - ``CryptContext(policy=CryptPolicy.from_string(data))``, can now be - done via ``CryptContext.from_string(data)``. - See :meth:`CryptContext.from_string` for details. - - Updating an existing CryptContext from a string, which was previously done - ``context.policy = CryptPolicy.from_string(data)``, can now be - done via ``context.load(data)``. - See :meth:`CryptContext.load` for details. - """ - warn(_preamble + - "Instead of ``CryptPolicy.from_string(source)``, " - "use ``CryptContext.from_string(source)`` or " - "``context.load(source)`` for an existing CryptContext.", - DeprecationWarning, stacklevel=2) - return cls(_internal_context=CryptContext.from_string(source, section, - encoding)) - - @classmethod - def from_source(cls, source, _warn=True): - """create a CryptPolicy instance from some source. - - this method autodetects the source type, and invokes - the appropriate constructor automatically. it attempts - to detect whether the source is a configuration string, a filepath, - a dictionary, or an existing CryptPolicy instance. - - .. deprecated:: 1.6 - - Create a new CryptContext, which could previously be done via - ``CryptContext(policy=CryptPolicy.from_source(source))``, should - now be done using an explicit method: the :class:`CryptContext` - constructor itself, :meth:`CryptContext.from_path`, - or :meth:`CryptContext.from_string`. - - Updating an existing CryptContext, which could previously be done via - ``context.policy = CryptPolicy.from_source(source)``, should - now be done using an explicit method: :meth:`CryptContext.update`, - or :meth:`CryptContext.load`. - """ - if _warn: - warn(_preamble + - "Instead of ``CryptPolicy.from_source()``, " - "use ``CryptContext.from_string(path)`` " - " or ``CryptContext.from_path(source)``, as appropriate.", - DeprecationWarning, stacklevel=2) - if isinstance(source, CryptPolicy): - return source - elif isinstance(source, dict): - return cls(_internal_context=CryptContext(**source)) - elif not isinstance(source, (bytes,unicode)): - raise TypeError("source must be CryptPolicy, dict, config string, " - "or file path: %r" % (type(source),)) - elif any(c in source for c in "\n\r\t") or not source.strip(" \t./\;:"): - return cls(_internal_context=CryptContext.from_string(source)) - else: - return cls(_internal_context=CryptContext.from_path(source)) - - @classmethod - def from_sources(cls, sources, _warn=True): - """create a CryptPolicy instance by merging multiple sources. - - each source is interpreted as by :meth:`from_source`, - and the results are merged together. - - .. deprecated:: 1.6 - Instead of using this method to merge multiple policies together, - a :class:`CryptContext` instance should be created, and then - the multiple sources merged together via :meth:`CryptContext.load`. - """ - if _warn: - warn(_preamble + - "Instead of ``CryptPolicy.from_sources()``, " - "use the various CryptContext constructors " - " followed by ``context.update()``.", - DeprecationWarning, stacklevel=2) - if len(sources) == 0: - raise ValueError("no sources specified") - if len(sources) == 1: - return cls.from_source(sources[0], _warn=False) - kwds = {} - for source in sources: - kwds.update(cls.from_source(source, _warn=False)._context.to_dict(resolve=True)) - return cls(_internal_context=CryptContext(**kwds)) - - def replace(self, *args, **kwds): - """create a new CryptPolicy, optionally updating parts of the - existing configuration. - - .. deprecated:: 1.6 - Callers of this method should :meth:`CryptContext.update` or - :meth:`CryptContext.copy` instead. - """ - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "Instead of ``context.policy.replace()``, " - "use ``context.update()`` or ``context.copy()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().replace()``, " - "create a CryptContext instance and " - "use ``context.update()`` or ``context.copy()``.", - DeprecationWarning, stacklevel=2) - sources = [ self ] - if args: - sources.extend(args) - if kwds: - sources.append(kwds) - return CryptPolicy.from_sources(sources, _warn=False) - - #=================================================================== - # instance attrs - #=================================================================== - - # internal CryptContext we're wrapping to handle everything - # until this class is removed. - _context = None - - # flag indicating this is wrapper generated by the CryptContext.policy - # attribute, rather than one created independantly by the application. - _stub_policy = False - - #=================================================================== - # init - #=================================================================== - def __init__(self, *args, **kwds): - context = kwds.pop("_internal_context", None) - if context: - assert isinstance(context, CryptContext) - self._context = context - self._stub_policy = kwds.pop("_stub_policy", False) - assert not (args or kwds), "unexpected args: %r %r" % (args,kwds) - else: - if args: - if len(args) != 1: - raise TypeError("only one positional argument accepted") - if kwds: - raise TypeError("cannot specify positional arg and kwds") - kwds = args[0] - warn(_preamble + - "Instead of constructing a CryptPolicy instance, " - "create a CryptContext directly, or use ``context.update()`` " - "and ``context.load()`` to reconfigure existing CryptContext " - "instances.", - DeprecationWarning, stacklevel=2) - self._context = CryptContext(**kwds) - - #=================================================================== - # public interface for examining options - #=================================================================== - def has_schemes(self): - """return True if policy defines *any* schemes for use. - - .. deprecated:: 1.6 - applications should use ``bool(context.schemes())`` instead. - see :meth:`CryptContext.schemes`. - """ - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "Instead of ``context.policy.has_schemes()``, " - "use ``bool(context.schemes())``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().has_schemes()``, " - "create a CryptContext instance and " - "use ``bool(context.schemes())``.", - DeprecationWarning, stacklevel=2) - return bool(self._context.schemes()) - - def iter_handlers(self): - """return iterator over handlers defined in policy. - - .. deprecated:: 1.6 - applications should use ``context.schemes(resolve=True))`` instead. - see :meth:`CryptContext.schemes`. - """ - if self._stub_policy: - warn(_preamble + - "Instead of ``context.policy.iter_handlers()``, " - "use ``context.schemes(resolve=True)``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().iter_handlers()``, " - "create a CryptContext instance and " - "use ``context.schemes(resolve=True)``.", - DeprecationWarning, stacklevel=2) - return self._context.schemes(resolve=True, unconfigured=True) - - def schemes(self, resolve=False): - """return list of schemes defined in policy. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.schemes` instead. - """ - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "Instead of ``context.policy.schemes()``, " - "use ``context.schemes()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().schemes()``, " - "create a CryptContext instance and " - "use ``context.schemes()``.", - DeprecationWarning, stacklevel=2) - return list(self._context.schemes(resolve=resolve, unconfigured=True)) - - def get_handler(self, name=None, category=None, required=False): - """return handler as specified by name, or default handler. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.handler` instead, - though note that the ``required`` keyword has been removed, - and the new method will always act as if ``required=True``. - """ - if self._stub_policy: - warn(_preamble + - "Instead of ``context.policy.get_handler()``, " - "use ``context.handler()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().get_handler()``, " - "create a CryptContext instance and " - "use ``context.handler()``.", - DeprecationWarning, stacklevel=2) - # CryptContext.handler() doesn't support required=False, - # so wrapping it in try/except - try: - return self._context.handler(name, category, unconfigured=True) - except KeyError: - if required: - raise - else: - return None - - def get_min_verify_time(self, category=None): - """get min_verify_time setting for policy. - - .. deprecated:: 1.6 - min_verify_time option will be removed entirely in passlib 1.8 - - .. versionchanged:: 1.7 - this method now always returns the value automatically - calculated by :meth:`CryptContext.min_verify_time`, - any value specified by policy is ignored. - """ - warn("get_min_verify_time() and min_verify_time option is deprecated and ignored, " - "and will be removed in Passlib 1.8", DeprecationWarning, - stacklevel=2) - context = self._context - if context.harden_verify: - return context.min_verify_time - else: - return 0 - - def get_options(self, name, category=None): - """return dictionary of options specific to a given handler. - - .. deprecated:: 1.6 - this method has no direct replacement in the 1.6 api, as there - is not a clearly defined use-case. however, examining the output of - :meth:`CryptContext.to_dict` should serve as the closest alternative. - """ - # XXX: might make a public replacement, but need more study of the use cases. - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "``context.policy.get_options()`` will no longer be available.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "``CryptPolicy().get_options()`` will no longer be available.", - DeprecationWarning, stacklevel=2) - if hasattr(name, "name"): - name = name.name - return self._context._config._get_record_options_with_flag(name, category)[0] - - def handler_is_deprecated(self, name, category=None): - """check if handler has been deprecated by policy. - - .. deprecated:: 1.6 - this method has no direct replacement in the 1.6 api, as there - is not a clearly defined use-case. however, examining the output of - :meth:`CryptContext.to_dict` should serve as the closest alternative. - """ - # XXX: might make a public replacement, but need more study of the use cases. - if self._stub_policy: - warn(_preamble + - "``context.policy.handler_is_deprecated()`` will no longer be available.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "``CryptPolicy().handler_is_deprecated()`` will no longer be available.", - DeprecationWarning, stacklevel=2) - if hasattr(name, "name"): - name = name.name - return self._context.handler(name, category).deprecated - - #=================================================================== - # serialization - #=================================================================== - - def iter_config(self, ini=False, resolve=False): - """iterate over key/value pairs representing the policy object. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.to_dict` instead. - """ - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "Instead of ``context.policy.iter_config()``, " - "use ``context.to_dict().items()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().iter_config()``, " - "create a CryptContext instance and " - "use ``context.to_dict().items()``.", - DeprecationWarning, stacklevel=2) - # hacked code that renders keys & values in manner that approximates - # old behavior. context.to_dict() is much cleaner. - context = self._context - if ini: - def render_key(key): - return context._render_config_key(key).replace("__", ".") - def render_value(value): - if isinstance(value, (list,tuple)): - value = ", ".join(value) - return value - resolve = False - else: - render_key = context._render_config_key - render_value = lambda value: value - return ( - (render_key(key), render_value(value)) - for key, value in context._config.iter_config(resolve) - ) - - def to_dict(self, resolve=False): - """export policy object as dictionary of options. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.to_dict` instead. - """ - if self._stub_policy: - warn(_preamble + - "Instead of ``context.policy.to_dict()``, " - "use ``context.to_dict()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().to_dict()``, " - "create a CryptContext instance and " - "use ``context.to_dict()``.", - DeprecationWarning, stacklevel=2) - return self._context.to_dict(resolve) - - def to_file(self, stream, section="passlib"): # pragma: no cover -- deprecated & unused - """export policy to file. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.to_string` instead, - and then write the output to a file as desired. - """ - if self._stub_policy: - warn(_preamble + - "Instead of ``context.policy.to_file(stream)``, " - "use ``stream.write(context.to_string())``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().to_file(stream)``, " - "create a CryptContext instance and " - "use ``stream.write(context.to_string())``.", - DeprecationWarning, stacklevel=2) - out = self._context.to_string(section=section) - if PY2: - out = out.encode("utf-8") - stream.write(out) - - def to_string(self, section="passlib", encoding=None): - """export policy to file. - - .. deprecated:: 1.6 - applications should use :meth:`CryptContext.to_string` instead. - """ - if self._stub_policy: - warn(_preamble + # pragma: no cover -- deprecated & unused - "Instead of ``context.policy.to_string()``, " - "use ``context.to_string()``.", - DeprecationWarning, stacklevel=2) - else: - warn(_preamble + - "Instead of ``CryptPolicy().to_string()``, " - "create a CryptContext instance and " - "use ``context.to_string()``.", - DeprecationWarning, stacklevel=2) - out = self._context.to_string(section=section) - if encoding: - out = out.encode(encoding) - return out - - #=================================================================== - # eoc - #=================================================================== - -#============================================================================= # _CryptConfig helper class #============================================================================= class _CryptConfig(object): @@ -735,8 +228,6 @@ class _CryptConfig(object): raise KeyError("'schemes' context option is not allowed " "per category") key, value = norm_context_option(cat, key, value) - if key == "min_verify_time": # ignored in 1.7, to be removed in 1.8 - continue # store in context_options # map structure: context_options[key][category] = value @@ -791,10 +282,6 @@ class _CryptConfig(object): if scheme not in schemes: raise KeyError("deprecated scheme not found " "in policy: %r" % (scheme,)) - elif key == "min_verify_time": - warn("'min_verify_time' was deprecated in Passlib 1.6, is " - "ignored in 1.7, and will be removed in 1.8; use 'harden_verify' instead", - DeprecationWarning) elif key == "harden_verify": if cat: raise ValueError("'harden_verify' cannot be specified per category") @@ -1349,7 +836,7 @@ class CryptContext(object): .. versionadded:: 1.6 This method was previously named :meth:`!replace`. That alias - has been deprecated, and will be removed in Passlib 1.8. + was removed in Passlib 1.8. .. seealso:: :meth:`update` """ @@ -1368,40 +855,18 @@ class CryptContext(object): """ return self.copy(**kwds) - def replace(self, **kwds): - """deprecated alias of :meth:`copy`""" - warn("CryptContext().replace() has been deprecated in Passlib 1.6, " - "and will be removed in Passlib 1.8, " - "it has been renamed to CryptContext().copy()", - DeprecationWarning, stacklevel=2) - return self.copy(**kwds) - #=================================================================== # init #=================================================================== def __init__(self, schemes=None, # keyword only... - policy=_UNSET, # <-- deprecated _autoload=True, **kwds): # XXX: add ability to make flag certain contexts as immutable, # e.g. the builtin passlib ones? # XXX: add a name or import path for the contexts, to help out repr? if schemes is not None: kwds['schemes'] = schemes - if policy is not _UNSET: - warn("The CryptContext ``policy`` keyword has been deprecated as of Passlib 1.6, " - "and will be removed in Passlib 1.8; please use " - "``CryptContext.from_string()` or " - "``CryptContext.from_path()`` instead.", - DeprecationWarning) - if policy is None: - self.load(kwds) - elif isinstance(policy, CryptPolicy): - self.load(policy._context) - self.update(kwds) - else: - raise TypeError("policy must be a CryptPolicy instance") - elif _autoload: + if _autoload: self.load(kwds) else: assert not kwds, "_autoload=False and kwds are mutually exclusive" @@ -1417,37 +882,6 @@ class CryptContext(object): return "<CryptContext at 0x%0x>" % id(self) #=================================================================== - # deprecated policy object - #=================================================================== - def _get_policy(self): - # The CryptPolicy class has been deprecated, so to support any - # legacy accesses, we create a stub policy object so .policy attr - # will continue to work. - # - # the code waits until app accesses a specific policy object attribute - # before issuing deprecation warning, so developer gets method-specific - # suggestion for how to upgrade. - - # NOTE: making a copy of the context so the policy acts like a snapshot, - # to retain the pre-1.6 behavior. - return CryptPolicy(_internal_context=self.copy(), _stub_policy=True) - - def _set_policy(self, policy): - warn("The CryptPolicy class and the ``context.policy`` attribute have " - "been deprecated as of Passlib 1.6, and will be removed in " - "Passlib 1.8; please use the ``context.load()`` and " - "``context.update()`` methods instead.", - DeprecationWarning, stacklevel=2) - if isinstance(policy, CryptPolicy): - self.load(policy._context) - else: - raise TypeError("expected CryptPolicy instance") - - policy = property(_get_policy, _set_policy, - doc="[deprecated] returns CryptPolicy instance " - "tied to this CryptContext") - - #=================================================================== # loading / updating configuration #=================================================================== @staticmethod @@ -1717,7 +1151,6 @@ class CryptContext(object): via the *schemes* option. .. versionadded:: 1.6 - This was previously available as ``CryptContext().policy.schemes()`` .. seealso:: the :ref:`schemes <context-schemes-option>` option for usage example. """ @@ -1813,7 +1246,6 @@ class CryptContext(object): be one of the objects from :mod:`passlib.hash`) .. versionadded:: 1.6 - This was previously available as ``CryptContext().policy.get_handler()`` .. versionchanged:: 1.7 @@ -1911,7 +1343,6 @@ class CryptContext(object): 'ldap_plaintext']} .. versionadded:: 1.6 - This was previously available as ``CryptContext().policy.to_dict()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. """ @@ -1953,7 +1384,6 @@ class CryptContext(object): schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext .. versionadded:: 1.6 - This was previously available as ``CryptContext().policy.to_string()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. """ @@ -2005,7 +1435,9 @@ class CryptContext(object): #: minimum measurement resolution required by estimate mvt_estimate_resolution = 0.05 - # XXX: make writable (once CryptPolicy is removed)? + # XXX: make writable? could store a lot of cryptcontext config directly in objects, + # (persisting hash state *in* the hashers), and then have to_dict() just extract + # current state. @memoized_property def harden_verify(self): return self._config.get_context_option_with_flag(None, "harden_verify")[0] @@ -2665,12 +2097,6 @@ class LazyCryptContext(CryptContext): .. versionadded:: 1.6 - :param create_policy: - - .. deprecated:: 1.6 - This option will be removed in Passlib 1.8, - applications should use ``onload`` instead. - :param kwds: All additional keywords are passed to CryptContext; @@ -2694,11 +2120,9 @@ class LazyCryptContext(CryptContext): """ _lazy_kwds = None - # NOTE: the way this class works changed in 1.6. - # previously it just called _lazy_init() when ``.policy`` was - # first accessed. now that is done whenever any of the public - # attributes are accessed, and the class itself is changed - # to a regular CryptContext, to remove the overhead once it's unneeded. + # NOTE: the way this class works is that whenever any of the public + # attributes are accessed, _lazy_init() is invoked, the class itself is changed + # to a regular CryptContext (to remove the overhead once it's unneeded) def __init__(self, schemes=None, **kwds): if schemes is not None: @@ -2707,17 +2131,7 @@ class LazyCryptContext(CryptContext): def _lazy_init(self): kwds = self._lazy_kwds - if 'create_policy' in kwds: - warn("The CryptPolicy class, and LazyCryptContext's " - "``create_policy`` keyword have been deprecated as of " - "Passlib 1.6, and will be removed in Passlib 1.8; " - "please use the ``onload`` keyword instead.", - DeprecationWarning) - create_policy = kwds.pop("create_policy") - result = create_policy(**kwds) - policy = CryptPolicy.from_source(result, _warn=False) - kwds = policy._context.to_dict() - elif 'onload' in kwds: + if 'onload' in kwds: onload = kwds.pop("onload") kwds = onload(**kwds) del self._lazy_kwds diff --git a/passlib/ext/django/utils.py b/passlib/ext/django/utils.py index a83cb89..96daa68 100644 --- a/passlib/ext/django/utils.py +++ b/passlib/ext/django/utils.py @@ -778,13 +778,7 @@ class DjangoContextAdapter(DjangoTranslator): config = getattr(settings, "PASSLIB_CONTEXT", _UNSET) if config is _UNSET: config = "passlib-default" - if config is None: - warn("setting PASSLIB_CONFIG=None is deprecated, " - "and support will be removed in Passlib 1.8, " - "use PASSLIB_CONFIG='disabled' instead.", - DeprecationWarning) - config = "disabled" - elif not isinstance(config, (unicode, bytes, dict)): + if not isinstance(config, (unicode, bytes, dict)): raise exc.ExpectedTypeError(config, "str or dict", "PASSLIB_CONFIG") # load custom category func (if any) diff --git a/passlib/handlers/misc.py b/passlib/handlers/misc.py index 44abc34..ecd2e78 100644 --- a/passlib/handlers/misc.py +++ b/passlib/handlers/misc.py @@ -15,66 +15,12 @@ import passlib.utils.handlers as uh # local __all__ = [ "unix_disabled", - "unix_fallback", "plaintext", ] #============================================================================= # handler #============================================================================= -class unix_fallback(uh.ifc.DisabledHash, uh.StaticHandler): - """This class provides the fallback behavior for unix shadow files, and follows the :ref:`password-hash-api`. - - This class does not implement a hash, but instead provides fallback - behavior as found in /etc/shadow on most unix variants. - If used, should be the last scheme in the context. - - * this class will positively identify all hash strings. - * for security, passwords will always hash to ``!``. - * it rejects all passwords if the hash is NOT an empty string (``!`` or ``*`` are frequently used). - * by default it rejects all passwords if the hash is an empty string, - but if ``enable_wildcard=True`` is passed to verify(), - all passwords will be allowed through if the hash is an empty string. - - .. deprecated:: 1.6 - This has been deprecated due to its "wildcard" feature, - and will be removed in Passlib 1.8. Use :class:`unix_disabled` instead. - """ - name = "unix_fallback" - context_kwds = ("enable_wildcard",) - - @classmethod - def identify(cls, hash): - if isinstance(hash, unicode_or_bytes_types): - return True - else: - raise uh.exc.ExpectedStringError(hash, "hash") - - def __init__(self, enable_wildcard=False, **kwds): - warn("'unix_fallback' is deprecated, " - "and will be removed in Passlib 1.8; " - "please use 'unix_disabled' instead.", - DeprecationWarning) - super(unix_fallback, self).__init__(**kwds) - self.enable_wildcard = enable_wildcard - - def _calc_checksum(self, secret): - if self.checksum: - # NOTE: hash will generally be "!", but we want to preserve - # it in case it's something else, like "*". - return self.checksum - else: - return u("!") - - @classmethod - def verify(cls, secret, hash, enable_wildcard=False): - uh.validate_secret(secret) - if not isinstance(hash, unicode_or_bytes_types): - raise uh.exc.ExpectedStringError(hash, "hash") - elif hash: - return False - else: - return enable_wildcard _MARKER_CHARS = u("*!") _MARKER_BYTES = b"*!" @@ -99,8 +45,8 @@ class unix_disabled(uh.ifc.DisabledHash, uh.MinimalHandler): (:attr:`!unix_disabled.default_marker` will contain the default value) .. versionadded:: 1.6 - This class was added as a replacement for the now-deprecated - :class:`unix_fallback` class, which had some undesirable features. + This class was added as a replacement for the now-removed + :class:`!unix_fallback` class. """ name = "unix_disabled" setting_kwds = ("marker",) diff --git a/passlib/handlers/windows.py b/passlib/handlers/windows.py index e17beba..8ccc8ee 100644 --- a/passlib/handlers/windows.py +++ b/passlib/handlers/windows.py @@ -180,14 +180,6 @@ class nthash(uh.StaticHandler): # XXX: found refs that say only first 128 chars are used. return md4(secret.encode("utf-16-le")).digest() - @classmethod - def raw_nthash(cls, secret, hex=False): - warn("nthash.raw_nthash() is deprecated, and will be removed " - "in Passlib 1.8, please use nthash.raw() instead", - DeprecationWarning) - ret = nthash.raw(secret) - return hexlify(ret).decode("ascii") if hex else ret - #=================================================================== # eoc #=================================================================== diff --git a/passlib/hash.py b/passlib/hash.py index 9b72448..eecbab1 100644 --- a/passlib/hash.py +++ b/passlib/hash.py @@ -45,7 +45,7 @@ if False: from passlib.handlers.fshp import fshp from passlib.handlers.ldap_digests import ldap_bcrypt, ldap_bsdi_crypt, ldap_des_crypt, ldap_md5, ldap_md5_crypt, ldap_plaintext, ldap_salted_md5, ldap_salted_sha1, ldap_sha1, ldap_sha1_crypt, ldap_sha256_crypt, ldap_sha512_crypt from passlib.handlers.md5_crypt import apr_md5_crypt, md5_crypt - from passlib.handlers.misc import plaintext, unix_disabled, unix_fallback + from passlib.handlers.misc import plaintext, unix_disabled from passlib.handlers.mssql import mssql2000, mssql2005 from passlib.handlers.mysql import mysql323, mysql41 from passlib.handlers.oracle import oracle10, oracle11 diff --git a/passlib/registry.py b/passlib/registry.py index d4ef6d0..803fb39 100644 --- a/passlib/registry.py +++ b/passlib/registry.py @@ -160,7 +160,6 @@ _locations = dict( sha512_crypt = "passlib.handlers.sha2_crypt", sun_md5_crypt = "passlib.handlers.sun_md5_crypt", unix_disabled = "passlib.handlers.misc", - unix_fallback = "passlib.handlers.misc", ) # master regexp for detecting valid handler names diff --git a/passlib/tests/test_apache.py b/passlib/tests/test_apache.py index c734c99..f4f91b4 100644 --- a/passlib/tests/test_apache.py +++ b/passlib/tests/test_apache.py @@ -63,8 +63,8 @@ class HtpasswdFileTest(TestCase): b'user6:$5$rounds=110000$cCRp/xUUGVgwR4aP$' b'p0.QKFS5qLNRqw1/47lXYiAcgIjJK.WjCO8nrEKuUK.\n') - def test_00_constructor_autoload(self): - """test constructor autoload""" + def test_00_constructor_new(self): + """constructor -- 'new' keyword""" # check with existing file path = self.mktemp() set_file(path, self.sample_01) @@ -84,13 +84,6 @@ class HtpasswdFileTest(TestCase): self.assertEqual(ht.path, path) self.assertFalse(ht.mtime) - # check autoload=False (deprecated alias for new=True) - with self.assertWarningList("``autoload=False`` is deprecated"): - ht = apache.HtpasswdFile(path, autoload=False) - self.assertEqual(ht.to_string(), b"") - self.assertEqual(ht.path, path) - self.assertFalse(ht.mtime) - # check missing file os.remove(path) self.assertRaises(IOError, apache.HtpasswdFile, path) @@ -137,21 +130,9 @@ class HtpasswdFileTest(TestCase): self.assertFalse(ht.set_password("user5", "pass5")) self.assertEqual(ht.to_string(), self.sample_03) - # test legacy default kwd - with self.assertWarningList("``default`` is deprecated"): - ht = apache.HtpasswdFile.from_string(self.sample_01, default="plaintext") - self.assertTrue(ht.set_password("user2", "pass2x")) - self.assertFalse(ht.set_password("user5", "pass5")) - self.assertEqual(ht.to_string(), self.sample_03) - # invalid user self.assertRaises(ValueError, ht.set_password, "user:", "pass") - # test that legacy update() still works - with self.assertWarningList("update\(\) is deprecated"): - ht.update("user2", "test") - self.assertTrue(ht.check_password("user2", "test")) - def test_02_set_password_autosave(self): path = self.mktemp() sample = b'user1:pass1\n' @@ -217,11 +198,6 @@ class HtpasswdFileTest(TestCase): self.assertRaises(ValueError, ht.check_password, "user:", "pass") - # test that legacy verify() still works - with self.assertWarningList(["verify\(\) is deprecated"]*2): - self.assertTrue(ht.verify("user1", "pass1")) - self.assertFalse(ht.verify("user1", "pass2")) - def test_05_load(self): """test load()""" # setup empty file @@ -291,10 +267,9 @@ class HtpasswdFileTest(TestCase): return_unicode=True) self.assertEqual(ht.users(), [ u("user\u00e6") ]) - # test deprecated encoding=None - with self.assertWarningList("``encoding=None`` is deprecated"): - ht = apache.HtpasswdFile.from_string(self.sample_04_utf8, encoding=None) - self.assertEqual(ht.users(), [ b'user\xc3\xa6' ]) + # encoding=None should throw error + self.assertRaises(TypeError, apache.HtpasswdFile.from_string, + self.sample_04_utf8, encoding=None) # check sample latin-1 ht = apache.HtpasswdFile.from_string(self.sample_04_latin1, @@ -308,9 +283,6 @@ class HtpasswdFileTest(TestCase): self.assertEqual(ht.get_hash("user4"), b"pass4") self.assertEqual(ht.get_hash("user5"), None) - with self.assertWarningList("find\(\) is deprecated"): - self.assertEqual(ht.find("user4"), b"pass4") - def test_09_to_string(self): """test to_string""" @@ -484,11 +456,6 @@ class HtdigestFileTest(TestCase): self.assertRaises(ValueError, ht.set_password, "user", "realm:", "pass") self.assertRaises(ValueError, ht.set_password, "user", "r"*256, "pass") - # test that legacy update() still works - with self.assertWarningList("update\(\) is deprecated"): - ht.update("user2", "realm2", "test") - self.assertTrue(ht.check_password("user2", "test")) - # TODO: test set_password autosave def test_03_users(self): @@ -518,11 +485,6 @@ class HtdigestFileTest(TestCase): self.assertTrue(ht.check_password("user1", "pass1")) self.assertIs(ht.check_password("user5", "pass5"), None) - # test that legacy verify() still works - with self.assertWarningList(["verify\(\) is deprecated"]*2): - self.assertTrue(ht.verify("user1", "realm", "pass1")) - self.assertFalse(ht.verify("user1", "realm", "pass2")) - # invalid user self.assertRaises(ValueError, ht.check_password, "user:", "realm", "pass") @@ -560,13 +522,6 @@ class HtdigestFileTest(TestCase): hc.load(path) self.assertEqual(hc.to_string(), self.sample_01) - # change file, test deprecated force=False kwd - ensure_mtime_changed(path) - set_file(path, "") - with self.assertWarningList(r"load\(force=False\) is deprecated"): - ha.load(force=False) - self.assertEqual(ha.to_string(), b"") - def test_06_save(self): """test save()""" # load from file @@ -607,9 +562,6 @@ class HtdigestFileTest(TestCase): self.assertEqual(ht.get_hash("user4", "realm"), "ab7b5d5f28ccc7666315f508c7358519") self.assertEqual(ht.get_hash("user5", "realm"), None) - with self.assertWarningList("find\(\) is deprecated"): - self.assertEqual(ht.find("user4", "realm"), "ab7b5d5f28ccc7666315f508c7358519") - def test_09_encodings(self): """test encoding parameter""" # test bad encodings cause failure in constructor diff --git a/passlib/tests/test_context_deprecated.py b/passlib/tests/test_context_deprecated.py deleted file mode 100644 index 0f76624..0000000 --- a/passlib/tests/test_context_deprecated.py +++ /dev/null @@ -1,743 +0,0 @@ -"""tests for passlib.context - -this file is a clone of the 1.5 test_context.py, -containing the tests using the legacy CryptPolicy api. -it's being preserved here to ensure the old api doesn't break -(until Passlib 1.8, when this and the legacy api will be removed). -""" -#============================================================================= -# imports -#============================================================================= -from __future__ import with_statement -# core -from logging import getLogger -import os -import warnings -# site -try: - from pkg_resources import resource_filename -except ImportError: - resource_filename = None -# pkg -from passlib import hash -from passlib.context import CryptContext, CryptPolicy, LazyCryptContext -from passlib.utils import to_bytes, to_unicode -import passlib.utils.handlers as uh -from passlib.tests.utils import TestCase, set_file -from passlib.registry import (register_crypt_handler_path, - _has_crypt_handler as has_crypt_handler, - _unload_handler_name as unload_handler_name, - ) -# module -log = getLogger(__name__) - -#============================================================================= -# -#============================================================================= -class CryptPolicyTest(TestCase): - """test CryptPolicy object""" - - # TODO: need to test user categories w/in all this - - descriptionPrefix = "CryptPolicy" - - #=================================================================== - # sample crypt policies used for testing - #=================================================================== - - #--------------------------------------------------------------- - # sample 1 - average config file - #--------------------------------------------------------------- - # NOTE: copy of this is stored in file passlib/tests/sample_config_1s.cfg - sample_config_1s = """\ -[passlib] -schemes = des_crypt, md5_crypt, bsdi_crypt, sha512_crypt -default = md5_crypt -all.vary_rounds = 10%% -bsdi_crypt.max_rounds = 30000 -bsdi_crypt.default_rounds = 25000 -sha512_crypt.max_rounds = 50000 -sha512_crypt.min_rounds = 40000 -""" - sample_config_1s_path = os.path.abspath(os.path.join( - os.path.dirname(__file__), "sample_config_1s.cfg")) - if not os.path.exists(sample_config_1s_path) and resource_filename: - # in case we're zipped up in an egg. - sample_config_1s_path = resource_filename("passlib.tests", - "sample_config_1s.cfg") - - # make sure sample_config_1s uses \n linesep - tests rely on this - assert sample_config_1s.startswith("[passlib]\nschemes") - - sample_config_1pd = dict( - schemes = [ "des_crypt", "md5_crypt", "bsdi_crypt", "sha512_crypt"], - default = "md5_crypt", - # NOTE: not maintaining backwards compat for rendering to "10%" - all__vary_rounds = 0.1, - bsdi_crypt__max_rounds = 30000, - bsdi_crypt__default_rounds = 25000, - sha512_crypt__max_rounds = 50000, - sha512_crypt__min_rounds = 40000, - ) - - sample_config_1pid = { - "schemes": "des_crypt, md5_crypt, bsdi_crypt, sha512_crypt", - "default": "md5_crypt", - # NOTE: not maintaining backwards compat for rendering to "10%" - "all.vary_rounds": 0.1, - "bsdi_crypt.max_rounds": 30000, - "bsdi_crypt.default_rounds": 25000, - "sha512_crypt.max_rounds": 50000, - "sha512_crypt.min_rounds": 40000, - } - - sample_config_1prd = dict( - schemes = [ hash.des_crypt, hash.md5_crypt, hash.bsdi_crypt, hash.sha512_crypt], - default = "md5_crypt", # NOTE: passlib <= 1.5 was handler obj. - # NOTE: not maintaining backwards compat for rendering to "10%" - all__vary_rounds = 0.1, - bsdi_crypt__max_rounds = 30000, - bsdi_crypt__default_rounds = 25000, - sha512_crypt__max_rounds = 50000, - sha512_crypt__min_rounds = 40000, - ) - - #--------------------------------------------------------------- - # sample 2 - partial policy & result of overlay on sample 1 - #--------------------------------------------------------------- - sample_config_2s = """\ -[passlib] -bsdi_crypt.min_rounds = 29000 -bsdi_crypt.max_rounds = 35000 -bsdi_crypt.default_rounds = 31000 -sha512_crypt.min_rounds = 45000 -""" - - sample_config_2pd = dict( - # using this to test full replacement of existing options - bsdi_crypt__min_rounds = 29000, - bsdi_crypt__max_rounds = 35000, - bsdi_crypt__default_rounds = 31000, - # using this to test partial replacement of existing options - sha512_crypt__min_rounds=45000, - ) - - sample_config_12pd = dict( - schemes = [ "des_crypt", "md5_crypt", "bsdi_crypt", "sha512_crypt"], - default = "md5_crypt", - # NOTE: not maintaining backwards compat for rendering to "10%" - all__vary_rounds = 0.1, - bsdi_crypt__min_rounds = 29000, - bsdi_crypt__max_rounds = 35000, - bsdi_crypt__default_rounds = 31000, - sha512_crypt__max_rounds = 50000, - sha512_crypt__min_rounds=45000, - ) - - #--------------------------------------------------------------- - # sample 3 - just changing default - #--------------------------------------------------------------- - sample_config_3pd = dict( - default="sha512_crypt", - ) - - sample_config_123pd = dict( - schemes = [ "des_crypt", "md5_crypt", "bsdi_crypt", "sha512_crypt"], - default = "sha512_crypt", - # NOTE: not maintaining backwards compat for rendering to "10%" - all__vary_rounds = 0.1, - bsdi_crypt__min_rounds = 29000, - bsdi_crypt__max_rounds = 35000, - bsdi_crypt__default_rounds = 31000, - sha512_crypt__max_rounds = 50000, - sha512_crypt__min_rounds=45000, - ) - - #--------------------------------------------------------------- - # sample 4 - category specific - #--------------------------------------------------------------- - sample_config_4s = """ -[passlib] -schemes = sha512_crypt -all.vary_rounds = 10%% -default.sha512_crypt.max_rounds = 20000 -admin.all.vary_rounds = 5%% -admin.sha512_crypt.max_rounds = 40000 -""" - - sample_config_4pd = dict( - schemes = [ "sha512_crypt" ], - # NOTE: not maintaining backwards compat for rendering to "10%" - all__vary_rounds = 0.1, - sha512_crypt__max_rounds = 20000, - # NOTE: not maintaining backwards compat for rendering to "5%" - admin__all__vary_rounds = 0.05, - admin__sha512_crypt__max_rounds = 40000, - ) - - #--------------------------------------------------------------- - # sample 5 - to_string & deprecation testing - #--------------------------------------------------------------- - sample_config_5s = sample_config_1s + """\ -deprecated = des_crypt -admin__context__deprecated = des_crypt, bsdi_crypt -""" - - sample_config_5pd = sample_config_1pd.copy() - sample_config_5pd.update( - deprecated = [ "des_crypt" ], - admin__context__deprecated = [ "des_crypt", "bsdi_crypt" ], - ) - - sample_config_5pid = sample_config_1pid.copy() - sample_config_5pid.update({ - "deprecated": "des_crypt", - "admin.context.deprecated": "des_crypt, bsdi_crypt", - }) - - sample_config_5prd = sample_config_1prd.copy() - sample_config_5prd.update({ - # XXX: should deprecated return the actual handlers in this case? - # would have to modify how policy stores info, for one. - "deprecated": ["des_crypt"], - "admin__context__deprecated": ["des_crypt", "bsdi_crypt"], - }) - - #=================================================================== - # constructors - #=================================================================== - def setUp(self): - TestCase.setUp(self) - warnings.filterwarnings("ignore", - r"The CryptPolicy class has been deprecated") - warnings.filterwarnings("ignore", - r"the method.*hash_needs_update.*is deprecated") - warnings.filterwarnings("ignore", "The 'all' scheme is deprecated.*") - warnings.filterwarnings("ignore", "bsdi_crypt rounds should be odd") - - def test_00_constructor(self): - """test CryptPolicy() constructor""" - policy = CryptPolicy(**self.sample_config_1pd) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - policy = CryptPolicy(self.sample_config_1pd) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - self.assertRaises(TypeError, CryptPolicy, {}, {}) - self.assertRaises(TypeError, CryptPolicy, {}, dummy=1) - - # check key with too many separators is rejected - self.assertRaises(TypeError, CryptPolicy, - schemes = [ "des_crypt", "md5_crypt", "bsdi_crypt", "sha512_crypt"], - bad__key__bsdi_crypt__max_rounds = 30000, - ) - - # check nameless handler rejected - class nameless(uh.StaticHandler): - name = None - self.assertRaises(ValueError, CryptPolicy, schemes=[nameless]) - - # check scheme must be name or crypt handler - self.assertRaises(TypeError, CryptPolicy, schemes=[uh.StaticHandler]) - - # check name conflicts are rejected - class dummy_1(uh.StaticHandler): - name = 'dummy_1' - self.assertRaises(KeyError, CryptPolicy, schemes=[dummy_1, dummy_1]) - - # with unknown deprecated value - self.assertRaises(KeyError, CryptPolicy, - schemes=['des_crypt'], - deprecated=['md5_crypt']) - - # with unknown default value - self.assertRaises(KeyError, CryptPolicy, - schemes=['des_crypt'], - default='md5_crypt') - - def test_01_from_path_simple(self): - """test CryptPolicy.from_path() constructor""" - # NOTE: this is separate so it can also run under GAE - - # test preset stored in existing file - path = self.sample_config_1s_path - policy = CryptPolicy.from_path(path) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test if path missing - self.assertRaises(EnvironmentError, CryptPolicy.from_path, path + 'xxx') - - def test_01_from_path(self): - """test CryptPolicy.from_path() constructor with encodings""" - path = self.mktemp() - - # test "\n" linesep - set_file(path, self.sample_config_1s) - policy = CryptPolicy.from_path(path) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test "\r\n" linesep - set_file(path, self.sample_config_1s.replace("\n","\r\n")) - policy = CryptPolicy.from_path(path) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test with custom encoding - uc2 = to_bytes(self.sample_config_1s, "utf-16", source_encoding="utf-8") - set_file(path, uc2) - policy = CryptPolicy.from_path(path, encoding="utf-16") - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - def test_02_from_string(self): - """test CryptPolicy.from_string() constructor""" - # test "\n" linesep - policy = CryptPolicy.from_string(self.sample_config_1s) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test "\r\n" linesep - policy = CryptPolicy.from_string( - self.sample_config_1s.replace("\n","\r\n")) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test with unicode - data = to_unicode(self.sample_config_1s) - policy = CryptPolicy.from_string(data) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test with non-ascii-compatible encoding - uc2 = to_bytes(self.sample_config_1s, "utf-16", source_encoding="utf-8") - policy = CryptPolicy.from_string(uc2, encoding="utf-16") - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # test category specific options - policy = CryptPolicy.from_string(self.sample_config_4s) - self.assertEqual(policy.to_dict(), self.sample_config_4pd) - - def test_03_from_source(self): - """test CryptPolicy.from_source() constructor""" - # pass it a path - policy = CryptPolicy.from_source(self.sample_config_1s_path) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # pass it a string - policy = CryptPolicy.from_source(self.sample_config_1s) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # pass it a dict (NOTE: make a copy to detect in-place modifications) - policy = CryptPolicy.from_source(self.sample_config_1pd.copy()) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # pass it existing policy - p2 = CryptPolicy.from_source(policy) - self.assertIs(policy, p2) - - # pass it something wrong - self.assertRaises(TypeError, CryptPolicy.from_source, 1) - self.assertRaises(TypeError, CryptPolicy.from_source, []) - - def test_04_from_sources(self): - """test CryptPolicy.from_sources() constructor""" - - # pass it empty list - self.assertRaises(ValueError, CryptPolicy.from_sources, []) - - # pass it one-element list - policy = CryptPolicy.from_sources([self.sample_config_1s]) - self.assertEqual(policy.to_dict(), self.sample_config_1pd) - - # pass multiple sources - policy = CryptPolicy.from_sources( - [ - self.sample_config_1s_path, - self.sample_config_2s, - self.sample_config_3pd, - ]) - self.assertEqual(policy.to_dict(), self.sample_config_123pd) - - def test_05_replace(self): - """test CryptPolicy.replace() constructor""" - - p1 = CryptPolicy(**self.sample_config_1pd) - - # check overlaying sample 2 - p2 = p1.replace(**self.sample_config_2pd) - self.assertEqual(p2.to_dict(), self.sample_config_12pd) - - # check repeating overlay makes no change - p2b = p2.replace(**self.sample_config_2pd) - self.assertEqual(p2b.to_dict(), self.sample_config_12pd) - - # check overlaying sample 3 - p3 = p2.replace(self.sample_config_3pd) - self.assertEqual(p3.to_dict(), self.sample_config_123pd) - - def test_06_forbidden(self): - """test CryptPolicy() forbidden kwds""" - - # salt not allowed to be set - self.assertRaises(KeyError, CryptPolicy, - schemes=["des_crypt"], - des_crypt__salt="xx", - ) - self.assertRaises(KeyError, CryptPolicy, - schemes=["des_crypt"], - all__salt="xx", - ) - - # schemes not allowed for category - self.assertRaises(KeyError, CryptPolicy, - schemes=["des_crypt"], - user__context__schemes=["md5_crypt"], - ) - - #=================================================================== - # reading - #=================================================================== - def test_10_has_schemes(self): - """test has_schemes() method""" - - p1 = CryptPolicy(**self.sample_config_1pd) - self.assertTrue(p1.has_schemes()) - - p3 = CryptPolicy(**self.sample_config_3pd) - self.assertTrue(not p3.has_schemes()) - - def test_11_iter_handlers(self): - """test iter_handlers() method""" - - p1 = CryptPolicy(**self.sample_config_1pd) - s = self.sample_config_1prd['schemes'] - self.assertEqual(list(p1.iter_handlers()), s) - - p3 = CryptPolicy(**self.sample_config_3pd) - self.assertEqual(list(p3.iter_handlers()), []) - - def test_12_get_handler(self): - """test get_handler() method""" - - p1 = CryptPolicy(**self.sample_config_1pd) - - # check by name - self.assertIs(p1.get_handler("bsdi_crypt"), hash.bsdi_crypt) - - # check by missing name - self.assertIs(p1.get_handler("sha256_crypt"), None) - self.assertRaises(KeyError, p1.get_handler, "sha256_crypt", required=True) - - # check default - self.assertIs(p1.get_handler(), hash.md5_crypt) - - def test_13_get_options(self): - """test get_options() method""" - - p12 = CryptPolicy(**self.sample_config_12pd) - - self.assertEqual(p12.get_options("bsdi_crypt"),dict( - # NOTE: not maintaining backwards compat for rendering to "10%" - vary_rounds = 0.1, - min_rounds = 29000, - max_rounds = 35000, - default_rounds = 31000, - )) - - self.assertEqual(p12.get_options("sha512_crypt"),dict( - # NOTE: not maintaining backwards compat for rendering to "10%" - vary_rounds = 0.1, - min_rounds = 45000, - max_rounds = 50000, - )) - - p4 = CryptPolicy.from_string(self.sample_config_4s) - self.assertEqual(p4.get_options("sha512_crypt"), dict( - # NOTE: not maintaining backwards compat for rendering to "10%" - vary_rounds=0.1, - max_rounds=20000, - )) - - self.assertEqual(p4.get_options("sha512_crypt", "user"), dict( - # NOTE: not maintaining backwards compat for rendering to "10%" - vary_rounds=0.1, - max_rounds=20000, - )) - - self.assertEqual(p4.get_options("sha512_crypt", "admin"), dict( - # NOTE: not maintaining backwards compat for rendering to "5%" - vary_rounds=0.05, - max_rounds=40000, - )) - - def test_14_handler_is_deprecated(self): - """test handler_is_deprecated() method""" - pa = CryptPolicy(**self.sample_config_1pd) - pb = CryptPolicy(**self.sample_config_5pd) - - self.assertFalse(pa.handler_is_deprecated("des_crypt")) - self.assertFalse(pa.handler_is_deprecated(hash.bsdi_crypt)) - self.assertFalse(pa.handler_is_deprecated("sha512_crypt")) - - self.assertTrue(pb.handler_is_deprecated("des_crypt")) - self.assertFalse(pb.handler_is_deprecated(hash.bsdi_crypt)) - self.assertFalse(pb.handler_is_deprecated("sha512_crypt")) - - # check categories as well - self.assertTrue(pb.handler_is_deprecated("des_crypt", "user")) - self.assertFalse(pb.handler_is_deprecated("bsdi_crypt", "user")) - self.assertTrue(pb.handler_is_deprecated("des_crypt", "admin")) - self.assertTrue(pb.handler_is_deprecated("bsdi_crypt", "admin")) - - # check deprecation is overridden per category - pc = CryptPolicy( - schemes=["md5_crypt", "des_crypt"], - deprecated=["md5_crypt"], - user__context__deprecated=["des_crypt"], - ) - self.assertTrue(pc.handler_is_deprecated("md5_crypt")) - self.assertFalse(pc.handler_is_deprecated("des_crypt")) - self.assertFalse(pc.handler_is_deprecated("md5_crypt", "user")) - self.assertTrue(pc.handler_is_deprecated("des_crypt", "user")) - - def test_15_min_verify_time(self): - """test get_min_verify_time() method""" - # silence deprecation warnings for min verify time - warnings.filterwarnings("ignore", category=DeprecationWarning) - - pa = CryptPolicy() - self.assertEqual(pa.get_min_verify_time(), 0) - self.assertEqual(pa.get_min_verify_time('admin'), 0) - - pb = pa.replace(min_verify_time=.1) - self.assertEqual(pb.get_min_verify_time(), 0) - self.assertEqual(pb.get_min_verify_time('admin'), 0) - - #=================================================================== - # serialization - #=================================================================== - def test_20_iter_config(self): - """test iter_config() method""" - p5 = CryptPolicy(**self.sample_config_5pd) - self.assertEqual(dict(p5.iter_config()), self.sample_config_5pd) - self.assertEqual(dict(p5.iter_config(resolve=True)), self.sample_config_5prd) - self.assertEqual(dict(p5.iter_config(ini=True)), self.sample_config_5pid) - - def test_21_to_dict(self): - """test to_dict() method""" - p5 = CryptPolicy(**self.sample_config_5pd) - self.assertEqual(p5.to_dict(), self.sample_config_5pd) - self.assertEqual(p5.to_dict(resolve=True), self.sample_config_5prd) - - def test_22_to_string(self): - """test to_string() method""" - pa = CryptPolicy(**self.sample_config_5pd) - s = pa.to_string() # NOTE: can't compare string directly, ordering etc may not match - pb = CryptPolicy.from_string(s) - self.assertEqual(pb.to_dict(), self.sample_config_5pd) - - s = pa.to_string(encoding="latin-1") - self.assertIsInstance(s, bytes) - - #=================================================================== - # - #=================================================================== - -#============================================================================= -# CryptContext -#============================================================================= -class CryptContextTest(TestCase): - """test CryptContext class""" - descriptionPrefix = "CryptContext" - - def setUp(self): - TestCase.setUp(self) - warnings.filterwarnings("ignore", - r"CryptContext\(\)\.replace\(\) has been deprecated.*") - warnings.filterwarnings("ignore", - r"The CryptContext ``policy`` keyword has been deprecated.*") - warnings.filterwarnings("ignore", ".*(CryptPolicy|context\.policy).*(has|have) been deprecated.*") - warnings.filterwarnings("ignore", - r"the method.*hash_needs_update.*is deprecated") - - #=================================================================== - # constructor - #=================================================================== - def test_00_constructor(self): - """test constructor""" - # create crypt context using handlers - cc = CryptContext([hash.md5_crypt, hash.bsdi_crypt, hash.des_crypt]) - c,b,a = cc.policy.iter_handlers() - self.assertIs(a, hash.des_crypt) - self.assertIs(b, hash.bsdi_crypt) - self.assertIs(c, hash.md5_crypt) - - # create context using names - cc = CryptContext(["md5_crypt", "bsdi_crypt", "des_crypt"]) - c,b,a = cc.policy.iter_handlers() - self.assertIs(a, hash.des_crypt) - self.assertIs(b, hash.bsdi_crypt) - self.assertIs(c, hash.md5_crypt) - - # policy kwd - policy = cc.policy - cc = CryptContext(policy=policy) - self.assertEqual(cc.to_dict(), policy.to_dict()) - - cc = CryptContext(policy=policy, default="bsdi_crypt") - self.assertNotEqual(cc.to_dict(), policy.to_dict()) - self.assertEqual(cc.to_dict(), dict(schemes=["md5_crypt","bsdi_crypt","des_crypt"], - default="bsdi_crypt")) - - self.assertRaises(TypeError, setattr, cc, 'policy', None) - self.assertRaises(TypeError, CryptContext, policy='x') - - def test_01_replace(self): - """test replace()""" - - cc = CryptContext(["md5_crypt", "bsdi_crypt", "des_crypt"]) - self.assertIs(cc.policy.get_handler(), hash.md5_crypt) - - cc2 = cc.replace() - self.assertIsNot(cc2, cc) - # NOTE: was not able to maintain backward compatibility with this... - ##self.assertIs(cc2.policy, cc.policy) - - cc3 = cc.replace(default="bsdi_crypt") - self.assertIsNot(cc3, cc) - # NOTE: was not able to maintain backward compatibility with this... - ##self.assertIs(cc3.policy, cc.policy) - self.assertIs(cc3.policy.get_handler(), hash.bsdi_crypt) - - def test_02_no_handlers(self): - """test no handlers""" - - # check constructor... - cc = CryptContext() - self.assertRaises(KeyError, cc.identify, 'hash', required=True) - self.assertRaises(KeyError, cc.hash, 'secret') - self.assertRaises(KeyError, cc.verify, 'secret', 'hash') - - # check updating policy after the fact... - cc = CryptContext(['md5_crypt']) - p = CryptPolicy(schemes=[]) - cc.policy = p - - self.assertRaises(KeyError, cc.identify, 'hash', required=True) - self.assertRaises(KeyError, cc.hash, 'secret') - self.assertRaises(KeyError, cc.verify, 'secret', 'hash') - - #=================================================================== - # policy adaptation - #=================================================================== - sample_policy_1 = dict( - schemes = [ "des_crypt", "md5_crypt", "phpass", "bsdi_crypt", - "sha256_crypt"], - deprecated = [ "des_crypt", ], - default = "sha256_crypt", - bsdi_crypt__max_rounds = 30, - bsdi_crypt__default_rounds = 25, - bsdi_crypt__vary_rounds = 0, - sha256_crypt__max_rounds = 3000, - sha256_crypt__min_rounds = 2000, - sha256_crypt__default_rounds = 3000, - phpass__ident = "H", - phpass__default_rounds = 7, - ) - - def test_12_hash_needs_update(self): - """test hash_needs_update() method""" - cc = CryptContext(**self.sample_policy_1) - - # check deprecated scheme - self.assertTrue(cc.hash_needs_update('9XXD4trGYeGJA')) - self.assertFalse(cc.hash_needs_update('$1$J8HC2RCr$HcmM.7NxB2weSvlw2FgzU0')) - - # check min rounds - self.assertTrue(cc.hash_needs_update('$5$rounds=1999$jD81UCoo.zI.UETs$Y7qSTQ6mTiU9qZB4fRr43wRgQq4V.5AAf7F97Pzxey/')) - self.assertFalse(cc.hash_needs_update('$5$rounds=2000$228SSRje04cnNCaQ$YGV4RYu.5sNiBvorQDlO0WWQjyJVGKBcJXz3OtyQ2u8')) - - # check max rounds - self.assertFalse(cc.hash_needs_update('$5$rounds=3000$fS9iazEwTKi7QPW4$VasgBC8FqlOvD7x2HhABaMXCTh9jwHclPA9j5YQdns.')) - self.assertTrue(cc.hash_needs_update('$5$rounds=3001$QlFHHifXvpFX4PLs$/0ekt7lSs/lOikSerQ0M/1porEHxYq7W/2hdFpxA3fA')) - - #=================================================================== - # border cases - #=================================================================== - def test_30_nonstring_hash(self): - """test non-string hash values cause error""" - warnings.filterwarnings("ignore", ".*needs_update.*'scheme' keyword is deprecated.*") - - # - # test hash=None or some other non-string causes TypeError - # and that explicit-scheme code path behaves the same. - # - cc = CryptContext(["des_crypt"]) - for hash, kwds in [ - (None, {}), - # NOTE: 'scheme' kwd is deprecated... - (None, {"scheme": "des_crypt"}), - (1, {}), - ((), {}), - ]: - - self.assertRaises(TypeError, cc.hash_needs_update, hash, **kwds) - - cc2 = CryptContext(["mysql323"]) - self.assertRaises(TypeError, cc2.hash_needs_update, None) - - #=================================================================== - # eoc - #=================================================================== - -#============================================================================= -# LazyCryptContext -#============================================================================= -class dummy_2(uh.StaticHandler): - name = "dummy_2" - -class LazyCryptContextTest(TestCase): - descriptionPrefix = "LazyCryptContext" - - def setUp(self): - TestCase.setUp(self) - - # make sure this isn't registered before OR after - unload_handler_name("dummy_2") - self.addCleanup(unload_handler_name, "dummy_2") - - # silence some warnings - warnings.filterwarnings("ignore", - r"CryptContext\(\)\.replace\(\) has been deprecated") - warnings.filterwarnings("ignore", ".*(CryptPolicy|context\.policy).*(has|have) been deprecated.*") - - def test_kwd_constructor(self): - """test plain kwds""" - self.assertFalse(has_crypt_handler("dummy_2")) - register_crypt_handler_path("dummy_2", "passlib.tests.test_context") - - cc = LazyCryptContext(iter(["dummy_2", "des_crypt"]), deprecated=["des_crypt"]) - - self.assertFalse(has_crypt_handler("dummy_2", True)) - - self.assertTrue(cc.policy.handler_is_deprecated("des_crypt")) - self.assertEqual(cc.policy.schemes(), ["dummy_2", "des_crypt"]) - - self.assertTrue(has_crypt_handler("dummy_2", True)) - - def test_callable_constructor(self): - """test create_policy() hook, returning CryptPolicy""" - self.assertFalse(has_crypt_handler("dummy_2")) - register_crypt_handler_path("dummy_2", "passlib.tests.test_context") - - def create_policy(flag=False): - self.assertTrue(flag) - return CryptPolicy(schemes=iter(["dummy_2", "des_crypt"]), deprecated=["des_crypt"]) - - cc = LazyCryptContext(create_policy=create_policy, flag=True) - - self.assertFalse(has_crypt_handler("dummy_2", True)) - - self.assertTrue(cc.policy.handler_is_deprecated("des_crypt")) - self.assertEqual(cc.policy.schemes(), ["dummy_2", "des_crypt"]) - - self.assertTrue(has_crypt_handler("dummy_2", True)) - -#============================================================================= -# eof -#============================================================================= diff --git a/passlib/tests/test_ext_django.py b/passlib/tests/test_ext_django.py index 25513fc..f566d13 100644 --- a/passlib/tests/test_ext_django.py +++ b/passlib/tests/test_ext_django.py @@ -607,9 +607,9 @@ class DjangoExtensionTest(_ExtensionTest): self.load_extension(PASSLIB_CONFIG="disabled", check=False) self.assert_unpatched() - # check legacy config=None - with self.assertWarningList("PASSLIB_CONFIG=None is deprecated"): - self.load_extension(PASSLIB_CONFIG=None, check=False) + # check onfig=None is rejected + self.assertRaises(TypeError, self.load_extension, PASSLIB_CONFIG=None, + check=False) self.assert_unpatched() # try stock django 1.0 context @@ -699,9 +699,9 @@ class DjangoExtensionTest(_ExtensionTest): #=================================================================== def test_11_config_disabled(self): """test PASSLIB_CONFIG='disabled'""" - # test config=None (deprecated) - with self.assertWarningList("PASSLIB_CONFIG=None is deprecated"): - self.load_extension(PASSLIB_CONFIG=None, check=False) + # test config=None is rejected + self.assertRaises(TypeError, self.load_extension, PASSLIB_CONFIG=None, + check=False) self.assert_unpatched() # test disabled config diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 08f19d4..72330be 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -1864,41 +1864,6 @@ class unix_disabled_test(HandlerCase): self.assertRaises(ValueError, handler.hash, 'stub', marker='abc') self.assertRaises(ValueError, handler.using, marker='abc') -class unix_fallback_test(HandlerCase): - handler = hash.unix_fallback - accepts_all_hashes = True - - known_correct_hashes = [ - # *everything* should hash to "!", and nothing should verify - ("password", "!"), - (UPASS_TABLE, "!"), - ] - - # silence annoying deprecation warning - def setUp(self): - super(unix_fallback_test, self).setUp() - warnings.filterwarnings("ignore", "'unix_fallback' is deprecated") - - def test_90_wildcard(self): - """test enable_wildcard flag""" - h = self.handler - self.assertTrue(h.verify('password','', enable_wildcard=True)) - self.assertFalse(h.verify('password','')) - for c in "!*x": - self.assertFalse(h.verify('password',c, enable_wildcard=True)) - self.assertFalse(h.verify('password',c)) - - def test_91_preserves_existing(self): - """test preserves existing disabled hash""" - handler = self.handler - - # use marker if no hash - self.assertEqual(handler.genhash("stub", ""), "!") - self.assertEqual(handler.hash("stub"), "!") - - # use hash if provided and valid - self.assertEqual(handler.genhash("stub", "!asd"), "!asd") - #============================================================================= # eof #============================================================================= diff --git a/passlib/tests/test_utils_handlers.py b/passlib/tests/test_utils_handlers.py index 19cd4ca..4f67006 100644 --- a/passlib/tests/test_utils_handlers.py +++ b/passlib/tests/test_utils_handlers.py @@ -90,54 +90,6 @@ class SkeletonTest(TestCase): self.assertEqual(d1.hash('s'), '_a') self.assertEqual(d1.hash('s', flag=True), '_b') - def test_01_calc_checksum_hack(self): - """test StaticHandler legacy attr""" - # release 1.5 StaticHandler required genhash(), - # not _calc_checksum, be implemented. we have backward compat wrapper, - # this tests that it works. - - class d1(uh.StaticHandler): - name = "d1" - - @classmethod - def identify(cls, hash): - if not hash or len(hash) != 40: - return False - try: - int(hash, 16) - except ValueError: - return False - return True - - @classmethod - def genhash(cls, secret, hash): - if secret is None: - raise TypeError("no secret provided") - if isinstance(secret, unicode): - secret = secret.encode("utf-8") - # NOTE: have to support hash=None since this is test of legacy 1.5 api - if hash is not None and not cls.identify(hash): - raise ValueError("invalid hash") - return hashlib.sha1(b"xyz" + secret).hexdigest() - - @classmethod - def verify(cls, secret, hash): - if hash is None: - raise ValueError("no hash specified") - return cls.genhash(secret, hash) == hash.lower() - - # hash should issue api warnings, but everything else should be fine. - with self.assertWarningList("d1.*should be updated.*_calc_checksum"): - hash = d1.hash("test") - self.assertEqual(hash, '7c622762588a0e5cc786ad0a143156f9fd38eea3') - - self.assertTrue(d1.verify("test", hash)) - self.assertFalse(d1.verify("xtest", hash)) - - # not defining genhash either, however, should cause NotImplementedError - del d1.genhash - self.assertRaises(NotImplementedError, d1.hash, 'test') - #=================================================================== # GenericHandler & mixins #=================================================================== diff --git a/passlib/tests/test_utils_pbkdf2.py b/passlib/tests/test_utils_pbkdf2.py index 3b2bd09..0be9752 100644 --- a/passlib/tests/test_utils_pbkdf2.py +++ b/passlib/tests/test_utils_pbkdf2.py @@ -23,60 +23,6 @@ from passlib.utils.compat import u, JYTHON from passlib.tests.utils import TestCase, hb #============================================================================= -# test assorted crypto helpers -#============================================================================= -class UtilsTest(TestCase): - """test various utils functions""" - descriptionPrefix = "passlib.utils.pbkdf2" - - ndn_formats = ["hashlib", "iana"] - ndn_values = [ - # (iana name, hashlib name, ... other unnormalized names) - ("md5", "md5", "SCRAM-MD5-PLUS", "MD-5"), - ("sha1", "sha-1", "SCRAM-SHA-1", "SHA1"), - ("sha256", "sha-256", "SHA_256", "sha2-256"), - ("ripemd", "ripemd", "SCRAM-RIPEMD", "RIPEMD"), - ("ripemd160", "ripemd-160", - "SCRAM-RIPEMD-160", "RIPEmd160"), - ("test128", "test-128", "TEST128"), - ("test2", "test2", "TEST-2"), - ("test3_128", "test3-128", "TEST-3-128"), - ] - - def setUp(self): - super(UtilsTest, self).setUp() - warnings.filterwarnings("ignore", ".*passlib.utils.pbkdf2.*deprecated", DeprecationWarning) - - def test_norm_hash_name(self): - """norm_hash_name()""" - from itertools import chain - from passlib.utils.pbkdf2 import norm_hash_name - from passlib.crypto.digest import _known_hash_names - - # test formats - for format in self.ndn_formats: - norm_hash_name("md4", format) - self.assertRaises(ValueError, norm_hash_name, "md4", None) - self.assertRaises(ValueError, norm_hash_name, "md4", "fake") - - # test types - self.assertEqual(norm_hash_name(u("MD4")), "md4") - self.assertEqual(norm_hash_name(b"MD4"), "md4") - self.assertRaises(TypeError, norm_hash_name, None) - - # test selected results - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", '.*unknown hash') - for row in chain(_known_hash_names, self.ndn_values): - for idx, format in enumerate(self.ndn_formats): - correct = row[idx] - for value in row: - result = norm_hash_name(value, format) - self.assertEqual(result, correct, - "name=%r, format=%r:" % (value, - format)) - -#============================================================================= # test PBKDF1 support #============================================================================= class Pbkdf1_Test(TestCase): diff --git a/passlib/tests/test_win32.py b/passlib/tests/test_win32.py deleted file mode 100644 index e818b62..0000000 --- a/passlib/tests/test_win32.py +++ /dev/null @@ -1,50 +0,0 @@ -"""tests for passlib.win32 -- (c) Assurance Technologies 2003-2009""" -#============================================================================= -# imports -#============================================================================= -# core -import warnings -# site -# pkg -from passlib.tests.utils import TestCase -# module -from passlib.utils.compat import u - -#============================================================================= -# -#============================================================================= -class UtilTest(TestCase): - """test util funcs in passlib.win32""" - - ##test hashes from http://msdn.microsoft.com/en-us/library/cc245828(v=prot.10).aspx - ## among other places - - def setUp(self): - super(UtilTest, self).setUp() - warnings.filterwarnings("ignore", - "the 'passlib.win32' module is deprecated") - - def test_lmhash(self): - from passlib.win32 import raw_lmhash - for secret, hash in [ - ("OLDPASSWORD", u("c9b81d939d6fd80cd408e6b105741864")), - ("NEWPASSWORD", u('09eeab5aa415d6e4d408e6b105741864')), - ("welcome", u("c23413a8a1e7665faad3b435b51404ee")), - ]: - result = raw_lmhash(secret, hex=True) - self.assertEqual(result, hash) - - def test_nthash(self): - warnings.filterwarnings("ignore", - r"nthash\.raw_nthash\(\) is deprecated") - from passlib.win32 import raw_nthash - for secret, hash in [ - ("OLDPASSWORD", u("6677b2c394311355b54f25eec5bfacf5")), - ("NEWPASSWORD", u("256781a62031289d3c2c98c14f1efc8c")), - ]: - result = raw_nthash(secret, hex=True) - self.assertEqual(result, hash) - -#============================================================================= -# eof -#============================================================================= diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py index fcc9686..3a65616 100644 --- a/passlib/utils/__init__.py +++ b/passlib/utils/__init__.py @@ -116,9 +116,6 @@ unix_crypt_schemes = [ # list of rounds_cost constants rounds_cost_values = [ "linear", "log2" ] -# legacy import, will be removed in 1.8 -from passlib.exc import MissingBackendError - # internal helpers _BEMPTY = b'' _UEMPTY = u("") diff --git a/passlib/utils/compat/__init__.py b/passlib/utils/compat/__init__.py index 1386b5c..41bef5a 100644 --- a/passlib/utils/compat/__init__.py +++ b/passlib/utils/compat/__init__.py @@ -112,6 +112,7 @@ else: native_string_types = (basestring,) # shorter preferred aliases +# TODO: align compat module w/ crowbar.compat naming unicode_or_bytes = unicode_or_bytes_types unicode_or_str = native_string_types diff --git a/passlib/utils/des.py b/passlib/utils/des.py index 034bfc4..1c407b9 100644 --- a/passlib/utils/des.py +++ b/passlib/utils/des.py @@ -17,30 +17,15 @@ warn("the 'passlib.utils.des' module has been relocated to 'passlib.crypto.des' from passlib.utils.decor import deprecated_function from passlib.crypto.des import expand_des_key, des_encrypt_block, des_encrypt_int_block -expand_des_key = deprecated_function(deprecated="1.7", removed="1.8", +expand_des_key = deprecated_function(deprecated="1.7", removed="2.0", replacement="passlib.crypto.des.expand_des_key")(expand_des_key) -des_encrypt_block = deprecated_function(deprecated="1.7", removed="1.8", +des_encrypt_block = deprecated_function(deprecated="1.7", removed="2.0", replacement="passlib.crypto.des.des_encrypt_block")(des_encrypt_block) -des_encrypt_int_block = deprecated_function(deprecated="1.7", removed="1.8", +des_encrypt_int_block = deprecated_function(deprecated="1.7", removed="2.0", replacement="passlib.crypto.des.des_encrypt_int_block")(des_encrypt_int_block) #============================================================================= -# deprecated functions -- not carried over to passlib.crypto.des -#============================================================================= -import struct -_unpack_uint64 = struct.Struct(">Q").unpack - -@deprecated_function(deprecated="1.6", removed="1.8", - replacement="passlib.crypto.des.des_encrypt_int_block()") -def mdes_encrypt_int_block(key, input, salt=0, rounds=1): # pragma: no cover -- deprecated & unused - if isinstance(key, bytes): - if len(key) == 7: - key = expand_des_key(key) - key = _unpack_uint64(key)[0] - return des_encrypt_int_block(key, input, salt, rounds) - -#============================================================================= # eof #============================================================================= diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index a0c1f51..ef553ab 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -927,45 +927,6 @@ class StaticHandler(GenericHandler): def to_string(self): return uascii_to_str(self._hash_prefix + self.checksum) - # per-subclass: stores dynamically created subclass used by _calc_checksum() stub - __cc_compat_hack = None - - def _calc_checksum(self, secret): - """given secret; calcuate and return encoded checksum portion of hash - string, taking config from object state - """ - # NOTE: prior to 1.6, StaticHandler required classes implement genhash - # instead of this method. so if we reach here, we try calling genhash. - # if that succeeds, we issue deprecation warning. if it fails, - # we'll just recurse back to here, but in a different instance. - # so before we call genhash, we create a subclass which handles - # throwing the NotImplementedError. - cls = self.__class__ - assert cls.__module__ != __name__ - wrapper_cls = cls.__cc_compat_hack - if wrapper_cls is None: - def inner(self, secret): - raise NotImplementedError("%s must implement _calc_checksum()" % - (cls,)) - wrapper_cls = cls.__cc_compat_hack = type(cls.__name__ + "_wrapper", - (cls,), dict(_calc_checksum=inner, __module__=cls.__module__)) - context = dict((k,getattr(self,k)) for k in self.context_kwds) - # NOTE: passing 'config=None' here even though not currently allowed by ifc, - # since it *is* allowed under the old 1.5 ifc we're checking for here. - try: - hash = wrapper_cls.genhash(secret, None, **context) - except TypeError as err: - if str(err) == "config must be string": - raise NotImplementedError("%s must implement _calc_checksum()" % - (cls,)) - else: - raise - warn("%r should be updated to implement StaticHandler._calc_checksum() " - "instead of StaticHandler.genhash(), support for the latter " - "style will be removed in Passlib 1.8" % cls, - DeprecationWarning) - return str_to_uascii(hash) - #============================================================================= # GenericHandler mixin classes #============================================================================= diff --git a/passlib/utils/pbkdf2.py b/passlib/utils/pbkdf2.py index 273143b..ad0a66e 100644 --- a/passlib/utils/pbkdf2.py +++ b/passlib/utils/pbkdf2.py @@ -12,14 +12,10 @@ import logging; log = logging.getLogger(__name__) # site # pkg from passlib.exc import ExpectedTypeError -from passlib.utils.decor import deprecated_function from passlib.utils.compat import native_string_types -from passlib.crypto.digest import norm_hash_name, lookup_hash, pbkdf1 as _pbkdf1, pbkdf2_hmac, compile_hmac +from passlib.crypto.digest import lookup_hash, pbkdf1 as _pbkdf1, pbkdf2_hmac, compile_hmac # local __all__ = [ - # hash utils - "norm_hash_name", - # prf utils "get_prf", @@ -38,13 +34,6 @@ warn("the module 'passlib.utils.pbkdf2' is deprecated as of Passlib 1.7, " DeprecationWarning) #============================================================================= -# hash helpers -#============================================================================= - -norm_hash_name = deprecated_function(deprecated="1.7", removed="1.8", func_module=__name__, - replacement="passlib.crypto.digest.norm_hash_name")(norm_hash_name) - -#============================================================================= # prf lookup #============================================================================= diff --git a/passlib/win32.py b/passlib/win32.py deleted file mode 100644 index 223dd6c..0000000 --- a/passlib/win32.py +++ /dev/null @@ -1,68 +0,0 @@ -"""passlib.win32 - MS Windows support - DEPRECATED, WILL BE REMOVED IN 1.8 - -the LMHASH and NTHASH algorithms are used in various windows related contexts, -but generally not in a manner compatible with how passlib is structured. - -in particular, they have no identifying marks, both being -32 bytes of binary data. thus, they can't be easily identified -in a context with other hashes, so a CryptHandler hasn't been defined for them. - -this module provided two functions to aid in any use-cases which exist. - -.. warning:: - - these functions should not be used for new code unless an existing - system requires them, they are both known broken, - and are beyond insecure on their own. - -.. autofunction:: raw_lmhash -.. autofunction:: raw_nthash - -See also :mod:`passlib.hash.nthash`. -""" - -from warnings import warn -warn("the 'passlib.win32' module is deprecated, and will be removed in " - "passlib 1.8; please use the 'passlib.hash.nthash' and " - "'passlib.hash.lmhash' classes instead.", - DeprecationWarning) - -#============================================================================= -# imports -#============================================================================= -# core -from binascii import hexlify -# site -# pkg -from passlib.utils.compat import unicode -from passlib.crypto.des import des_encrypt_block -from passlib.hash import nthash -# local -__all__ = [ - "nthash", - "raw_lmhash", - "raw_nthash", -] -#============================================================================= -# helpers -#============================================================================= -LM_MAGIC = b"KGS!@#$%" - -raw_nthash = nthash.raw_nthash - -def raw_lmhash(secret, encoding="ascii", hex=False): - """encode password using des-based LMHASH algorithm; returns string of raw bytes, or unicode hex""" - # NOTE: various references say LMHASH uses the OEM codepage of the host - # for its encoding. until a clear reference is found, - # as well as a path for getting the encoding, - # letting this default to "ascii" to prevent incorrect hashes - # from being made w/o user explicitly choosing an encoding. - if isinstance(secret, unicode): - secret = secret.encode(encoding) - ns = secret.upper()[:14] + b"\x00" * (14-len(secret)) - out = des_encrypt_block(ns[:7], LM_MAGIC) + des_encrypt_block(ns[7:], LM_MAGIC) - return hexlify(out).decode("ascii") if hex else out - -#============================================================================= -# eoc -#============================================================================= |
