cryptacular / cryptacular / core / __init__.py

# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Daniel Holth <dholth@fastmail.fm>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

__all__ = [
    'DelegatingPasswordManager',
    'PasswordChecker',
    'PasswordManager',
    'check_unicode'
]


if 'unicode' in __builtins__:
    def check_unicode(text):
        if isinstance(text, unicode):
            text = text.encode('utf-8')
        return text
else:
    def check_unicode(text):
        return text


class PasswordChecker(object):

    SCHEME = None
    PREFIX = None

    def check(self, encoded, password):
        """Return True if 'password' hashes to 'encoded' in this scheme.

        Most password schemes require encoded and password to be byte
        strings. The schemes included with this package convert unicode
        'encoded' and 'password' to utf-8 as necessary.
        """
        raise NotImplementedError()

    def match(self, encoded):
        """Return True if 'encoded' appears to be a valid hash for this scheme.

        Most password schemes include a recognizable prefix in their hashes."""
        return encoded.startswith(self.PREFIX)


class PasswordManager(PasswordChecker):

    def encode(self, password):
        """Return hash of 'password' using this scheme.
        """
        raise NotImplementedError()


class DelegatingPasswordManager(object):

    SCHEME = None
    PREFIX = None

    def __init__(self, fallbacks=(), **kwargs):
        self._managers = [kwargs['preferred']]
        self._managers.extend(fallbacks)

    @property
    def preferred(self):
        return self._managers[0]

    @property
    def fallbacks(self):
        return self._managers[1:]

    def encode(self, password):
        return self.preferred.encode(password)

    def check(self, encoded, password, setter=None):
        for i, manager in enumerate(self._managers):
            if manager.match(encoded):
                valid = manager.check(encoded, password)
                if valid and i > 0 and setter is not None:
                    setter(self.preferred.encode(password))
                return valid

        raise ValueError("No configured password manager for given hash.")

    def match(self, encoded):
        return True in [m.match(encoded) for m in self._managers]


def _cmp(a, b):
    """Constant-time comparison.
    """
    if len(a) != len(b):
        return False

    result = 0
    for x, y in zip(a, b):
        result |= ord(x) ^ ord(y)
    return result == 0
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.