当前位置: 首页>>代码示例>>Python>>正文


Python utils.constant_time_compare函数代码示例

本文整理汇总了Python中r2.lib.utils.constant_time_compare函数的典型用法代码示例。如果您正苦于以下问题:Python constant_time_compare函数的具体用法?Python constant_time_compare怎么用?Python constant_time_compare使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了constant_time_compare函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: valid_password

def valid_password(a, password):
    # bail out early if the account or password's invalid
    if not hasattr(a, 'name') or not hasattr(a, 'password') or not password:
        return False

    # standardize on utf-8 encoding
    password = filters._force_utf8(password)

    # this is really easy if it's a sexy bcrypt password
    if a.password.startswith('$2a$'):
        expected_hash = bcrypt.hashpw(password, a.password)
        if constant_time_compare(a.password, expected_hash):
            return a
        return False

    # alright, so it's not bcrypt. how old is it?
    # if the length of the stored hash is 43 bytes, the sha-1 hash has a salt
    # otherwise it's sha-1 with no salt.
    salt = ''
    if len(a.password) == 43:
        salt = a.password[:3]
    expected_hash = passhash(a.name, password, salt)

    if not constant_time_compare(a.password, expected_hash):
        return False

    # since we got this far, it's a valid password but in an old format
    # let's upgrade it
    a.password = bcrypt_password(password)
    a._commit()
    return a
开发者ID:Chris911,项目名称:reddit,代码行数:31,代码来源:account.py

示例2: valid_password

def valid_password(a, password, compare_password=None):
    # bail out early if the account or password's invalid
    if not hasattr(a, 'name') or not hasattr(a, 'password') or not password:
        return False

    convert_password = False
    if compare_password is None:
        convert_password = True
        compare_password = a.password

    # standardize on utf-8 encoding
    password = filters._force_utf8(password)

    if compare_password.startswith('$2a$'):
        # it's bcrypt.

        try:
            expected_hash = bcrypt.hashpw(password, compare_password)
        except ValueError:
            # password is invalid because it contains null characters
            return False

        if not constant_time_compare(compare_password, expected_hash):
            return False

        # if it's using the current work factor, we're done, but if it's not
        # we'll have to rehash.
        # the format is $2a$workfactor$salt+hash
        work_factor = int(compare_password.split("$")[2])
        if work_factor == g.bcrypt_work_factor:
            return a
    else:
        # alright, so it's not bcrypt. how old is it?
        # if the length of the stored hash is 43 bytes, the sha-1 hash has a salt
        # otherwise it's sha-1 with no salt.
        salt = ''
        if len(compare_password) == 43:
            salt = compare_password[:3]
        expected_hash = passhash(a.name, password, salt)

        if not constant_time_compare(compare_password, expected_hash):
            return False

    # since we got this far, it's a valid password but in an old format
    # let's upgrade it
    if convert_password:
        a.password = bcrypt_password(password)
        a._commit()
    return a
开发者ID:AHAMED750,项目名称:reddit,代码行数:49,代码来源:account.py

示例3: valid_password

def valid_password(a, password):
    try:
        # A constant_time_compare isn't strictly required here
        # but it is doesn't hurt
        if constant_time_compare(a.password, passhash(a.name, password, '')):
            #add a salt
            a.password = passhash(a.name, password, True)
            a._commit()
            return a
        else:
            salt = a.password[:3]
            if constant_time_compare(a.password, passhash(a.name, password, salt)):
                return a
    except AttributeError, UnicodeEncodeError:
        return False
开发者ID:CrazyNomnom,项目名称:reddit,代码行数:15,代码来源:account.py

示例4: get_authenticated_account

    def get_authenticated_account(self):
        from r2.models import Account, NotFound

        quoted_session_cookie = request.cookies.get(g.login_cookie)
        if not quoted_session_cookie:
            return None
        session_cookie = urllib.unquote(quoted_session_cookie)

        try:
            uid, timestr, hash = session_cookie.split(",")
            uid = int(uid)
        except:
            return None

        try:
            account = Account._byID(uid, data=True)
        except NotFound:
            return None

        expected_cookie = account.make_cookie(timestr)
        if not constant_time_compare(session_cookie, expected_cookie):
            return None
        
        if not hooks.get_hook("enhanced.privacy.check").call_until_return(uid=uid, hash=hash):
            return None
        
        return account
开发者ID:mewald55,项目名称:BlockPath,代码行数:27,代码来源:cookie.py

示例5: GET_mediaembed

    def GET_mediaembed(self, link, credentials):
        if request.host != g.media_domain:
            # don't serve up untrusted content except on our
            # specifically untrusted domain
            abort(404)

        if link.subreddit_slow.type in Subreddit.private_types:
            expected_mac = hmac.new(g.secrets["media_embed"], link._id36,
                                    hashlib.sha1).hexdigest()
            if not constant_time_compare(credentials or "", expected_mac):
                abort(404)

        if not c.secure:
            media_object = link.media_object
        else:
            media_object = link.secure_media_object

        if not media_object:
            abort(404)
        elif isinstance(media_object, dict):
            # otherwise it's the new style, which is a dict(type=type, **args)
            media_embed = get_media_embed(media_object)
            content = media_embed.content

        c.allow_framing = True

        return MediaEmbedBody(body = content).render()
开发者ID:AjaxGb,项目名称:reddit,代码行数:27,代码来源:mediaembed.py

示例6: get_authenticated_account

    def get_authenticated_account(self):
        from r2.models import Account, NotFound, register

        try:
            authorization = request.environ.get("HTTP_AUTHORIZATION")
            username, password = parse_http_basic(authorization)
        except RequirementException:
            return None

        try:
            account = Account._by_name(username)
        except NotFound:
            if g.auth_trust_http_authorization:
                # note: we're explicitly allowing automatic re-registration of
                # _deleted accounts and login of _banned accounts here because
                # we're trusting you know what you're doing in an SSO situation
                account = register(username, password, request.ip)
            else:
                return None

        # if we're to trust the authorization headers, don't check passwords
        if g.auth_trust_http_authorization:
            return account

        # not all systems support bcrypt in the standard crypt
        if account.password.startswith("$2a$"):
            expected_hash = bcrypt.hashpw(password, account.password)
        else:
            expected_hash = crypt.crypt(password, account.password)

        if not constant_time_compare(expected_hash, account.password):
            return None
        return account
开发者ID:APerson241,项目名称:reddit,代码行数:33,代码来源:http.py

示例7: set_up_embed

def set_up_embed(embed_key, sr, thing, showedits):
    expected_mac = hmac.new(g.secrets["comment_embed"], thing._id36, hashlib.sha1).hexdigest()
    if not constant_time_compare(embed_key or "", expected_mac):
        abort(401)

    try:
        author = Account._byID(thing.author_id) if thing.author_id else None
    except NotFound:
        author = None

    iso_timestamp = request.GET.get("created", "")

    c.embed_config = {
        "eventtracker_url": g.eventtracker_url or "",
        "anon_eventtracker_url": g.anon_eventtracker_url or "",
        "created": iso_timestamp,
        "showedits": showedits,
        "thing": {
            "id": thing._id,
            "sr_id": sr._id,
            "sr_name": sr.name,
            "edited": edited_after(thing, iso_timestamp, showedits),
            "deleted": thing.deleted or author._deleted,
        },
    }

    c.render_style = "iframe"
    c.user = UnloggedUser([c.lang])
    c.user_is_loggedin = False
    c.forced_loggedout = True
开发者ID:SovietMan,项目名称:reddit,代码行数:30,代码来源:embeds.py

示例8: POST_timings

    def POST_timings(self, action_name, verification, **kwargs):
        lookup = {
            "dns_timing": "dns",
            "tcp_timing": "tcp",
            "request_timing": "request",
            "response_timing": "response",
            "dom_loading_timing": "dom_loading",
            "dom_interactive_timing": "dom_interactive",
            "dom_content_loaded_timing": "dom_content_loaded",
        }

        if not (action_name and verification):
            abort(422)

        expected_mac = hmac.new(g.secrets["action_name"], action_name, hashlib.sha1).hexdigest()

        if not constant_time_compare(verification, expected_mac):
            abort(422)

        # action_name comes in the format 'controller.METHOD_action'
        stat_tpl = "service_time.web.{}.frontend".format(action_name)
        stat_aggregate = "service_time.web.frontend"

        for key, name in lookup.iteritems():
            val = kwargs[key]
            if val >= 0:
                g.stats.simple_timing(stat_tpl + "." + name, val)
                g.stats.simple_timing(stat_aggregate + "." + name, val)

        abort(204)
开发者ID:annerajb,项目名称:reddit,代码行数:30,代码来源:web.py

示例9: parse_and_validate_reply_to_address

def parse_and_validate_reply_to_address(address):
    """Validate the address and parse out and return the message id.

    This is the reverse operation of `get_reply_to_address`.

    """

    recipient, sep, domain = address.partition("@")
    if not sep or not recipient or domain != g.modmail_email_domain:
        return

    main, sep, remainder = recipient.partition("+")
    if not sep or not main or main != "zendeskreply":
        return

    try:
        email_id, email_mac = remainder.split("-")
    except ValueError:
        return

    expected_mac = hmac.new(
        g.secrets['modmail_email_secret'], email_id, hashlib.sha256).hexdigest()

    if not constant_time_compare(expected_mac, email_mac):
        return

    message_id36 = email_id
    return message_id36
开发者ID:AHAMED750,项目名称:reddit,代码行数:28,代码来源:message_to_email.py

示例10: valid_admin_cookie

def valid_admin_cookie(cookie):
    if g.read_only_mode:
        return (False, None)

    # parse the cookie
    try:
        first_login, last_request, hash = cookie.split(',')
    except ValueError:
        return (False, None)

    # make sure it's a recent cookie
    try:
        first_login_time = datetime.strptime(first_login, COOKIE_TIMESTAMP_FORMAT)
        last_request_time = datetime.strptime(last_request, COOKIE_TIMESTAMP_FORMAT)
    except ValueError:
        return (False, None)

    cookie_age = datetime.utcnow() - first_login_time
    if cookie_age.total_seconds() > g.ADMIN_COOKIE_TTL:
        return (False, None)

    idle_time = datetime.utcnow() - last_request_time
    if idle_time.total_seconds() > g.ADMIN_COOKIE_MAX_IDLE:
        return (False, None)

    # validate
    expected_cookie = c.user.make_admin_cookie(first_login, last_request)
    return (constant_time_compare(cookie, expected_cookie),
            first_login)
开发者ID:XPRIYA,项目名称:HMWK2PartB,代码行数:29,代码来源:account.py

示例11: _get_client_auth

 def _get_client_auth(self):
     auth = request.headers.get("Authorization")
     try:
         client_id, client_secret = parse_http_basic(auth)
         client = OAuth2Client.get_token(client_id)
         require(client)
         require(constant_time_compare(client.secret, client_secret))
         return client
     except RequirementException:
         abort(401, headers=[("WWW-Authenticate", 'Basic realm="reddit"')])
开发者ID:Bebetz,项目名称:reddit,代码行数:10,代码来源:oauth2.py

示例12: valid_feed

def valid_feed(name, feedhash, path):
    if name and feedhash and path:
        from r2.lib.template_helpers import add_sr
        path = add_sr(path)
        try:
            user = Account._by_name(name)
            if (user.pref_private_feeds and
                constant_time_compare(feedhash, make_feedhash(user, path))):
                return user
        except NotFound:
            pass
开发者ID:XPRIYA,项目名称:HMWK2PartB,代码行数:11,代码来源:account.py

示例13: valid_cookie

def valid_cookie(cookie):
    try:
        uid, timestr, hash = cookie.split(',')
        uid = int(uid)
    except:
        return (False, False)

    if g.read_only_mode:
        return (False, False)

    try:
        account = Account._byID(uid, True)
        if account._deleted:
            return (False, False)
    except NotFound:
        return (False, False)

    if constant_time_compare(cookie, account.make_cookie(timestr, admin = False)):
        return (account, False)
    elif constant_time_compare(cookie, account.make_cookie(timestr, admin = True)):
        return (account, True)
    return (False, False)
开发者ID:Chris911,项目名称:reddit,代码行数:22,代码来源:account.py

示例14: POST_revoke_token

    def POST_revoke_token(self, token_id, token_hint):
        '''Revoke an OAuth2 access or refresh token.

        token_type_hint is optional, and hints to the server
        whether the passed token is a refresh or access token.

        A call to this endpoint is considered a success if
        the passed `token_id` is no longer valid. Thus, if an invalid
        `token_id` was passed in, a successful 204 response will be returned.

        See [RFC7009](http://tools.ietf.org/html/rfc7009)

        '''
        self.OPTIONS_revoke_token()
        # In success cases, this endpoint returns no data.
        response.status = 204

        if not token_id:
            return

        types = (OAuth2AccessToken, OAuth2RefreshToken)
        if token_hint == "refresh_token":
            types = reversed(types)

        for token_type in types:
            try:
                token = token_type._byID(token_id)
            except tdb_cassandra.NotFound:
                g.stats.simple_event(
                    'oauth2.POST_revoke_token.cass_not_found.%s'
                    % token_type.__name__)
                continue
            else:
                break
        else:
            # No Token found. The given token ID is already gone
            # or never existed. Either way, from the client's perspective,
            # the passed in token is no longer valid.
            return

        if constant_time_compare(token.client_id, c.oauth2_client._id):
            token.revoke()
        else:
            # RFC 7009 is not clear on how to handle this case.
            # Given that a malicious client could do much worse things
            # with a valid token then revoke it, returning an error
            # here is best as it may help certain clients debug issues
            response.status = 400
            g.stats.simple_event(
                'oauth2.errors.REVOKE_TOKEN_UNAUTHORIZED_CLIENT')
            return self.api_wrapper({"error": "unauthorized_client"})
开发者ID:AHAMED750,项目名称:reddit,代码行数:51,代码来源:oauth2.py

示例15: get_client_ip

    def get_client_ip(self, environ):
        try:
            client_ip = environ["HTTP_CF_CONNECTING_IP"]
            provided_hash = environ["HTTP_CF_CIP_TAG"].lower()
        except KeyError:
            return None

        secret = g.secrets["cdn_ip_verification"]
        expected_hash = hashlib.sha1(client_ip + secret).hexdigest()

        if not constant_time_compare(expected_hash, provided_hash):
            return None

        return client_ip
开发者ID:GodOfConquest,项目名称:reddit,代码行数:14,代码来源:cloudflare.py


注:本文中的r2.lib.utils.constant_time_compare函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。