def verifyPassword(password):
    newhash = scrypt.hash(password, Salt, 1 << N, r, p, hLen)
    # We use a contstant-time comparison function from passlib.utils.consteq to mitigate timing attacks.
    if consteq(newhash, Hash):
        print("La contraseña '" + password + "' es correcta")
    else:
        print("La contraseña '" + password + "' es incorrecta")
示例#2
0
文件: misc.py 项目: thebaron/passlib
 def verify(cls, secret, hash, encoding=None):
     if not encoding:
         encoding = cls.default_encoding
     hash = to_native_str(hash, encoding, "hash")
     if not cls.identify(hash):
         raise uh.exc.InvalidHashError(cls)
     return consteq(cls.encrypt(secret, encoding), hash)
示例#3
0
    def verify(cls, secret, hash, full=False):
        uh.validate_secret(secret)
        self = cls.from_string(hash)
        chkmap = self.checksum
        if not chkmap:
            raise ValueError("expected %s hash, got %s config string instead" %
                             (cls.name, cls.name))

        # NOTE: to make the verify method efficient, we just calculate hash
        # of shortest digest by default. apps can pass in "full=True" to
        # check entire hash for consistency.
        if full:
            correct = failed = False
            for alg, digest in iteritems(chkmap):
                other = self._calc_checksum(secret, alg)
                # NOTE: could do this length check in norm_algs(),
                # but don't need to be that strict, and want to be able
                # to parse hashes containing algs not supported by platform.
                # it's fine if we fail here though.
                if len(digest) != len(other):
                    raise ValueError(
                        "mis-sized %s digest in scram hash: %r != %r" %
                        (alg, len(digest), len(other)))
                if consteq(other, digest):
                    correct = True
                else:
                    failed = True
            if correct and failed:
                raise ValueError("scram hash verified inconsistently, "
                                 "may be corrupted")
            else:
                return correct
        else:
            # XXX: should this just always use sha1 hash? would be faster.
            # otherwise only verify against one hash, pick one w/ best security.
            for alg in self._verify_algs:
                if alg in chkmap:
                    other = self._calc_checksum(secret, alg)
                    return consteq(other, chkmap[alg])
            # there should always be sha-1 at the very least,
            # or something went wrong inside _norm_algs()
            raise AssertionError("sha-1 digest not found!")
示例#4
0
文件: scram.py 项目: cutso/passlib
    def verify(cls, secret, hash, full=False):
        uh.validate_secret(secret)
        self = cls.from_string(hash)
        chkmap = self.checksum
        if not chkmap:
            raise ValueError("expected %s hash, got %s config string instead" %
                             (cls.name, cls.name))

        # NOTE: to make the verify method efficient, we just calculate hash
        # of shortest digest by default. apps can pass in "full=True" to
        # check entire hash for consistency.
        if full:
            correct = failed = False
            for alg, digest in iteritems(chkmap):
                other = self._calc_checksum(secret, alg)
                # NOTE: could do this length check in norm_algs(),
                # but don't need to be that strict, and want to be able
                # to parse hashes containing algs not supported by platform.
                # it's fine if we fail here though.
                if len(digest) != len(other):
                    raise ValueError("mis-sized %s digest in scram hash: %r != %r"
                                     % (alg, len(digest), len(other)))
                if consteq(other, digest):
                    correct = True
                else:
                    failed = True
            if correct and failed:
                raise ValueError("scram hash verified inconsistently, "
                                 "may be corrupted")
            else:
                return correct
        else:
            # XXX: should this just always use sha1 hash? would be faster.
            # otherwise only verify against one hash, pick one w/ best security.
            for alg in self._verify_algs:
                if alg in chkmap:
                    other = self._calc_checksum(secret, alg)
                    return consteq(other, chkmap[alg])
            # there should always be sha-1 at the very least,
            # or something went wrong inside _norm_algs()
            raise AssertionError("sha-1 digest not found!")
示例#5
0
 def verify(cls, secret, hash):
     # NOTE: we only compare against the upper-case hash
     # XXX: add 'full' just to verify both checksums?
     uh.validate_secret(secret)
     self = cls.from_string(hash)
     chk = self.checksum
     if chk is None:
         raise uh.exc.MissingDigestError(cls)
     if isinstance(secret, bytes):
         secret = secret.decode("utf-8")
     result = _raw_mssql(secret.upper(), self.salt)
     return consteq(result, chk[20:])
示例#6
0
文件: mssql.py 项目: cutso/passlib
 def verify(cls, secret, hash):
     # NOTE: we only compare against the upper-case hash
     # XXX: add 'full' just to verify both checksums?
     uh.validate_secret(secret)
     self = cls.from_string(hash)
     chk = self.checksum
     if chk is None:
         raise uh.exc.MissingDigestError(cls)
     if isinstance(secret, bytes):
         secret = secret.decode("utf-8")
     result = _raw_mssql(secret.upper(), self.salt)
     return consteq(result, chk[20:])
示例#7
0
    def verify_secret(self, secret):
        u"""
        Returns True if secret is equal to user's secret.

        **Example usage**

        >>> import copy
        >>> from .models_test import USER_TEST
        >>> user = copy.copy(USER_TEST)
        >>> assert(not user.verify_secret(u'bad_secret'))
        >>> assert(user.verify_secret(u'Secr4taB'))
        >>> user.hash_secret()
        >>> assert(not user.verify_secret(u'bad_secret'))
        >>> assert(user.verify_secret(u'Secr4taB'))
        """
        if self.is_secret_hashed:
            return pbkdf2_sha512.verify(secret, self.secret)
        return consteq(secret, self.secret)
示例#8
0
    def test_consteq(self):
        "test consteq()"
        # NOTE: this test is kind of over the top, but that's only because
        # this is used for the critical task of comparing hashes for equality.
        from passlib.utils import consteq

        # ensure error raises for wrong types
        self.assertRaises(TypeError, consteq, u(''), b(''))
        self.assertRaises(TypeError, consteq, u(''), 1)
        self.assertRaises(TypeError, consteq, u(''), None)

        self.assertRaises(TypeError, consteq, b(''), u(''))
        self.assertRaises(TypeError, consteq, b(''), 1)
        self.assertRaises(TypeError, consteq, b(''), None)

        self.assertRaises(TypeError, consteq, None, u(''))
        self.assertRaises(TypeError, consteq, None, b(''))
        self.assertRaises(TypeError, consteq, 1, u(''))
        self.assertRaises(TypeError, consteq, 1, b(''))

        # check equal inputs compare correctly
        for value in [
                u("a"),
                u("abc"),
                u("\xff\xa2\x12\x00") * 10,
        ]:
            self.assertTrue(consteq(value, value), "value %r:" % (value, ))
            value = value.encode("latin-1")
            self.assertTrue(consteq(value, value), "value %r:" % (value, ))

        # check non-equal inputs compare correctly
        for l, r in [
                # check same-size comparisons with differing contents fail.
            (u("a"), u("c")),
            (u("abcabc"), u("zbaabc")),
            (u("abcabc"), u("abzabc")),
            (u("abcabc"), u("abcabz")),
            ((u("\xff\xa2\x12\x00") * 10)[:-1] + u("\x01"),
             u("\xff\xa2\x12\x00") * 10),

                # check different-size comparisons fail.
            (u(""), u("a")),
            (u("abc"), u("abcdef")),
            (u("abc"), u("defabc")),
            (u("qwertyuiopasdfghjklzxcvbnm"), u("abc")),
        ]:
            self.assertFalse(consteq(l, r), "values %r %r:" % (l, r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r, l))
            l = l.encode("latin-1")
            r = r.encode("latin-1")
            self.assertFalse(consteq(l, r), "values %r %r:" % (l, r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r, l))
示例#9
0
    def test_consteq(self):
        "test consteq()"
        # NOTE: this test is kind of over the top, but that's only because
        # this is used for the critical task of comparing hashes for equality.
        from passlib.utils import consteq

        # ensure error raises for wrong types
        self.assertRaises(TypeError, consteq, u(''), b(''))
        self.assertRaises(TypeError, consteq, u(''), 1)
        self.assertRaises(TypeError, consteq, u(''), None)

        self.assertRaises(TypeError, consteq, b(''), u(''))
        self.assertRaises(TypeError, consteq, b(''), 1)
        self.assertRaises(TypeError, consteq, b(''), None)

        self.assertRaises(TypeError, consteq, None, u(''))
        self.assertRaises(TypeError, consteq, None, b(''))
        self.assertRaises(TypeError, consteq, 1, u(''))
        self.assertRaises(TypeError, consteq, 1, b(''))

        # check equal inputs compare correctly
        for value in [
                u("a"),
                u("abc"),
                u("\xff\xa2\x12\x00")*10,
            ]:
            self.assertTrue(consteq(value, value), "value %r:" % (value,))
            value = value.encode("latin-1")
            self.assertTrue(consteq(value, value), "value %r:" % (value,))

        # check non-equal inputs compare correctly
        for l,r in [
                # check same-size comparisons with differing contents fail.
                (u("a"),         u("c")),
                (u("abcabc"),    u("zbaabc")),
                (u("abcabc"),    u("abzabc")),
                (u("abcabc"),    u("abcabz")),
                ((u("\xff\xa2\x12\x00")*10)[:-1] + u("\x01"),
                    u("\xff\xa2\x12\x00")*10),

                # check different-size comparisons fail.
                (u(""),       u("a")),
                (u("abc"),    u("abcdef")),
                (u("abc"),    u("defabc")),
                (u("qwertyuiopasdfghjklzxcvbnm"), u("abc")),
            ]:
            self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
            l = l.encode("latin-1")
            r = r.encode("latin-1")
            self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
示例#10
0
文件: mongo.py 项目: zlorb/pytoolbox
    def verify_secret(self, secret):
        """
        Returns True if secret is equal to user's secret.

        **Example usage**

        >>> user = User(first_name='D.', last_name='F.', mail='*****@*****.**', secret='Secr4taB', admin_platform=True)
        >>> user.verify_secret('bad_secret')
        False
        >>> user.verify_secret('Secr4taB')
        True
        >>> user.hash_secret()
        >>> user.verify_secret('bad_secret')
        False
        >>> user.verify_secret('Secr4taB')
        True
        """
        if self.is_secret_hashed:
            return pbkdf2_sha512.verify(secret, self.secret)
        return consteq(secret, self.secret)
示例#11
0
    def verify_secret(self, secret):
        """
        Returns True if secret is equal to user's secret.

        **Example usage**

        >>> user = User(first_name='D.', last_name='F.', mail='*****@*****.**', secret='Secr4taB', admin_platform=True)
        >>> user.verify_secret('bad_secret')
        False
        >>> user.verify_secret('Secr4taB')
        True
        >>> user.hash_secret()
        >>> user.verify_secret('bad_secret')
        False
        >>> user.verify_secret('Secr4taB')
        True
        """
        if self.is_secret_hashed:
            return pbkdf2_sha512.verify(secret, self.secret)
        return consteq(secret, self.secret)
示例#12
0
def valid_token(key, token, timeout=2 * 60 * 60):
    """
    check if token is valid with respect to the secret key,
    the token must not be older than timeout seconds.

    :param key: give the secret key to verify the token
    :param token: the token to verify
    :param timeout: timeout seconds, set to None to ignore timeout
    :rtype: bool
    :returns: token is valid and not timed out
    """
    parts = token.split('-')
    if len(parts) != 2:
        return False
    try:
        stamp = int(parts[0])
    except ValueError:
        return False
    if timeout and stamp + timeout < time.time():
        return False
    expected_token = generate_token(key, stamp)[1]
    return consteq(token, expected_token)
示例#13
0
文件: crypto.py 项目: wobsta/moin
def valid_token(key, token, timeout=2 * 60 * 60):
    """
    check if token is valid with respect to the secret key,
    the token must not be older than timeout seconds.

    :param key: give the secret key to verify the token
    :param token: the token to verify
    :param timeout: timeout seconds, set to None to ignore timeout
    :rtype: bool
    :returns: token is valid and not timed out
    """
    parts = token.split('-')
    if len(parts) != 2:
        return False
    try:
        stamp = int(parts[0])
    except ValueError:
        return False
    if timeout and stamp + timeout < time.time():
        return False
    expected_token = generate_token(key, stamp)[1]
    return consteq(token, expected_token)
示例#14
0
def digest_compare(left, right):
    return consteq(left.encode("utf-8"), right.encode("utf-8"))
示例#15
0
def digest_compare(left, right):
    return consteq(left.encode('utf-8'), right.encode('utf-8'))
示例#16
0
def verify_password(password, verifier):
    logN, r, p, salt, hash_value = unpack_verifier(verifier)
    newhash = scrypt.hash(password, salt, 1 << logN, r, p, len(hash_value))
    return consteq(newhash, hash_value)
示例#17
0
 def verify(cls, secret, hash, user, realm, encoding="utf-8"):
     hash = cls._norm_hash(hash)
     other = cls.encrypt(secret, user, realm, encoding)
     return consteq(hash, other)
示例#18
0
def verify_password( password, verifier ):
    logN,r,p,salt,hash = unpack_verifier(verifier)
    newhash = scrypt.hash(password,salt,1<<logN,r,p,len(hash))
    return consteq(newhash,hash)
示例#19
0
文件: auth.py 项目: mbr/dope
 def verify(self, creds):
     if consteq(creds.password, current_app.config[self.varname]):
         return creds.username
示例#20
0
    def test_consteq(self):
        """test consteq()"""
        # NOTE: this test is kind of over the top, but that's only because
        # this is used for the critical task of comparing hashes for equality.
        from passlib.utils import consteq, str_consteq

        # ensure error raises for wrong types
        self.assertRaises(TypeError, consteq, u(''), b'')
        self.assertRaises(TypeError, consteq, u(''), 1)
        self.assertRaises(TypeError, consteq, u(''), None)

        self.assertRaises(TypeError, consteq, b'', u(''))
        self.assertRaises(TypeError, consteq, b'', 1)
        self.assertRaises(TypeError, consteq, b'', None)

        self.assertRaises(TypeError, consteq, None, u(''))
        self.assertRaises(TypeError, consteq, None, b'')
        self.assertRaises(TypeError, consteq, 1, u(''))
        self.assertRaises(TypeError, consteq, 1, b'')

        def consteq_supports_string(value):
            # under PY2, it supports all unicode strings (when present at all),
            # under PY3, compare_digest() only supports ascii unicode strings.
            # confirmed for: cpython 2.7.9, cpython 3.4, pypy, pypy3, pyston
            return (consteq is str_consteq or PY2 or is_ascii_safe(value))

        # check equal inputs compare correctly
        for value in [
                u("a"),
                u("abc"),
                u("\xff\xa2\x12\x00")*10,
            ]:
            if consteq_supports_string(value):
                self.assertTrue(consteq(value, value), "value %r:" % (value,))
            else:
                self.assertRaises(TypeError, consteq, value, value)
            self.assertTrue(str_consteq(value, value), "value %r:" % (value,))

            value = value.encode("latin-1")
            self.assertTrue(consteq(value, value), "value %r:" % (value,))

        # check non-equal inputs compare correctly
        for l,r in [
                # check same-size comparisons with differing contents fail.
                (u("a"),         u("c")),
                (u("abcabc"),    u("zbaabc")),
                (u("abcabc"),    u("abzabc")),
                (u("abcabc"),    u("abcabz")),
                ((u("\xff\xa2\x12\x00")*10)[:-1] + u("\x01"),
                    u("\xff\xa2\x12\x00")*10),

                # check different-size comparisons fail.
                (u(""),       u("a")),
                (u("abc"),    u("abcdef")),
                (u("abc"),    u("defabc")),
                (u("qwertyuiopasdfghjklzxcvbnm"), u("abc")),
            ]:
            if consteq_supports_string(l) and consteq_supports_string(r):
                self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
                self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
            else:
                self.assertRaises(TypeError, consteq, l, r)
                self.assertRaises(TypeError, consteq, r, l)
            self.assertFalse(str_consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(str_consteq(r, l), "values %r %r:" % (r,l))

            l = l.encode("latin-1")
            r = r.encode("latin-1")
            self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
示例#21
0
文件: util.py 项目: schu/bookmarks
def cmp_hash(a, b):
    return consteq(to_bytes(a), to_bytes(b))
示例#22
0
    def test_consteq(self):
        """test consteq()"""
        # NOTE: this test is kind of over the top, but that's only because
        # this is used for the critical task of comparing hashes for equality.
        from passlib.utils import consteq, str_consteq

        # ensure error raises for wrong types
        self.assertRaises(TypeError, consteq, u(''), b'')
        self.assertRaises(TypeError, consteq, u(''), 1)
        self.assertRaises(TypeError, consteq, u(''), None)

        self.assertRaises(TypeError, consteq, b'', u(''))
        self.assertRaises(TypeError, consteq, b'', 1)
        self.assertRaises(TypeError, consteq, b'', None)

        self.assertRaises(TypeError, consteq, None, u(''))
        self.assertRaises(TypeError, consteq, None, b'')
        self.assertRaises(TypeError, consteq, 1, u(''))
        self.assertRaises(TypeError, consteq, 1, b'')

        def consteq_supports_string(value):
            # under PY2, it supports all unicode strings (when present at all),
            # under PY3, compare_digest() only supports ascii unicode strings.
            # confirmed for: cpython 2.7.9, cpython 3.4, pypy, pypy3, pyston
            return (consteq is str_consteq or PY2 or is_ascii_safe(value))

        # check equal inputs compare correctly
        for value in [
                u("a"),
                u("abc"),
                u("\xff\xa2\x12\x00")*10,
            ]:
            if consteq_supports_string(value):
                self.assertTrue(consteq(value, value), "value %r:" % (value,))
            else:
                self.assertRaises(TypeError, consteq, value, value)
            self.assertTrue(str_consteq(value, value), "value %r:" % (value,))

            value = value.encode("latin-1")
            self.assertTrue(consteq(value, value), "value %r:" % (value,))

        # check non-equal inputs compare correctly
        for l,r in [
                # check same-size comparisons with differing contents fail.
                (u("a"),         u("c")),
                (u("abcabc"),    u("zbaabc")),
                (u("abcabc"),    u("abzabc")),
                (u("abcabc"),    u("abcabz")),
                ((u("\xff\xa2\x12\x00")*10)[:-1] + u("\x01"),
                    u("\xff\xa2\x12\x00")*10),

                # check different-size comparisons fail.
                (u(""),       u("a")),
                (u("abc"),    u("abcdef")),
                (u("abc"),    u("defabc")),
                (u("qwertyuiopasdfghjklzxcvbnm"), u("abc")),
            ]:
            if consteq_supports_string(l) and consteq_supports_string(r):
                self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
                self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
            else:
                self.assertRaises(TypeError, consteq, l, r)
                self.assertRaises(TypeError, consteq, r, l)
            self.assertFalse(str_consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(str_consteq(r, l), "values %r %r:" % (r,l))

            l = l.encode("latin-1")
            r = r.encode("latin-1")
            self.assertFalse(consteq(l, r), "values %r %r:" % (l,r))
            self.assertFalse(consteq(r, l), "values %r %r:" % (r,l))
示例#23
0
 def verify(cls, secret, hash, user, realm, encoding="utf-8"):
     hash = cls._norm_hash(hash)
     other = cls.hash(secret, user, realm, encoding)
     return consteq(hash, other)