當前位置: 首頁>>代碼示例>>Python>>正文


Python fernet.InvalidToken方法代碼示例

本文整理匯總了Python中cryptography.fernet.InvalidToken方法的典型用法代碼示例。如果您正苦於以下問題:Python fernet.InvalidToken方法的具體用法?Python fernet.InvalidToken怎麽用?Python fernet.InvalidToken使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cryptography.fernet的用法示例。


在下文中一共展示了fernet.InvalidToken方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: load_session

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def load_session(self, request):
        cookie = self.load_cookie(request)
        if cookie is None:
            return Session(None, data=None, new=True, max_age=self.max_age)
        else:
            try:
                data = self._decoder(
                    self._fernet.decrypt(
                        cookie.encode('utf-8'),
                        ttl=self.max_age
                    ).decode('utf-8')
                )
                return Session(None, data=data,
                               new=False, max_age=self.max_age)
            except InvalidToken:
                log.warning("Cannot decrypt cookie value, "
                            "create a new fresh session")
                return Session(None, data=None, new=True, max_age=self.max_age) 
開發者ID:aio-libs,項目名稱:aiohttp-session,代碼行數:20,代碼來源:cookie_storage.py

示例2: get_val

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def get_val(self):
        """
        Get Airflow Variable from Metadata DB and decode it using the Fernet Key
        """
        if self._val is not None and self.is_encrypted:
            try:
                fernet = get_fernet()
                return fernet.decrypt(bytes(self._val, 'utf-8')).decode()
            except InvalidFernetToken:
                self.log.error("Can't decrypt _val for key=%s, invalid token or value", self.key)
                return None
            except Exception:  # pylint: disable=broad-except
                self.log.error("Can't decrypt _val for key=%s, FERNET_KEY configuration missing", self.key)
                return None
        else:
            return self._val 
開發者ID:apache,項目名稱:airflow,代碼行數:18,代碼來源:variable.py

示例3: decrypt_string

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def decrypt_string(string, key, ttl=None):
    """
    Decrypts an encrypted string with the specified key.

    The key must be 32 raw bytes.
    """
    f = Fernet(key)

    # Fernet() works only on byte objects. Convert the string to bytes before decrypting.
    encrypted_bytes = string.encode()  # str -> bytes

    try:
        decrypted_bytes = f.decrypt(encrypted_bytes, ttl=ttl)
    except InvalidToken:
        """
        From the the Cryptography's library documentation:

        If the token is in any way invalid, this exception is raised.
        A token may be invalid for a number of reasons: it is older than the
        ttl, it is malformed, or it does not have a valid signature.
        """
        return None  # TODO(kmullins): Shall we log this case? Is it expected?

    decrypted_string = decrypted_bytes.decode()  # bytes -> str
    return decrypted_string 
開發者ID:quay,項目名稱:quay,代碼行數:27,代碼來源:crypto.py

示例4: test_assures_data_integrity

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def test_assures_data_integrity(self):
        self.write_secret()
        testdata = factory.make_bytes(size=10)
        token = fernet_encrypt_psk(testdata)
        bad_token = bytearray(token)
        # Flip a bit in the token, so we can ensure it won't decrypt if it
        # has been corrupted. Subtract 4 to avoid the end of the token; that
        # portion is just padding, and isn't covered by the HMAC.
        byte_to_flip = randint(0, len(bad_token) - 4)
        bit_to_flip = 1 << randint(0, 7)
        bad_token[byte_to_flip] ^= bit_to_flip
        bad_token = bytes(bad_token)
        test_description = "token=%s; token[%d] ^= 0x%02x" % (
            token.decode("utf-8"),
            byte_to_flip,
            bit_to_flip,
        )
        with ExpectedException(InvalidToken, msg=test_description):
            fernet_decrypt_psk(bad_token) 
開發者ID:maas,項目名稱:maas,代碼行數:21,代碼來源:test_security.py

示例5: decrypt

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def decrypt(password):
    encrypted_passwords = config().get('Security', 'encrypted_credentials') == 'y'
    if not encrypted_passwords:
        return password

    try:
        f = Fernet(_get_key())
        return f.decrypt(password)
    except InvalidToken:
        print("Invalid master password")
        sys.exit(-1) 
開發者ID:rtshome,項目名稱:pgrepup,代碼行數:13,代碼來源:crypt.py

示例6: read_secret

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def read_secret(slug: str, passphrase: str) -> Tuple[Dict, int]:
    """Read a secret.

    Args:
        slug (str): Unique slug link to access the secret.
        passphrase (str): Passphrase needed to decrypt the secret.

    """
    secret = Entries.query.filter_by(slug_link=slug).first()
    if not secret:
        app.logger.warning(
            f"{slug} tried to read but do not exists in database")
        return dict(status=Status.EXPIRED.value,
                    msg=("Sorry, we can't find a secret, it has expired, "
                         "been deleted or has already been read.")), 404

    try:
        msg = Secret(secret.encrypted_text, passphrase).decrypt()
    except InvalidToken:
        remaining = secret.tries - 1
        if remaining == 0:
            # Number of tries exceeded
            app.logger.warning(f"{slug} tries to open secret exceeded")
            secret.delete()
            return dict(
                status=Status.INVALID.value,
                msg=("The passphrase is not valid. You've exceeded the "
                     "number of tries and the secret has been deleted.")), 401

        secret.update(tries=remaining)
        app.logger.warning(f"{slug} wrong passphrase used. "
                           f"Number of tries remaining: {remaining}")
        return dict(status=Status.INVALID.value,
                    msg=("Sorry the passphrase is not valid. "
                         f"Number of tries remaining: {remaining}")), 401

    secret.delete()  # Delete message after it's read
    app.logger.info(f"{slug} was decrypted and deleted")
    return dict(status=Status.SUCCESS.value, msg=html.escape(msg)), 200 
開發者ID:smallwat3r,項目名稱:shhh,代碼行數:41,代碼來源:utils.py

示例7: test_wrong_passphrase

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def test_wrong_passphrase(self):
        with self.assertRaises(InvalidToken):
            Secret(self.encrypted_text, "wrongPassphrase").decrypt() 
開發者ID:smallwat3r,項目名稱:shhh,代碼行數:5,代碼來源:test_secret_encryption.py

示例8: decrypt

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def decrypt(data, encryption_key=None):
    if data is None:
        return None

    encryption_key = get_valid_encryption_key(encryption_key)
    encoded_key = base64.b64encode(encryption_key.encode('utf-8'))
    sym = fernet.Fernet(encoded_key)
    try:
        value = sym.decrypt(encodeutils.safe_encode(data))
        if value is not None:
            return encodeutils.safe_decode(value, 'utf-8')
    except fernet.InvalidToken:
        raise exception.InvalidEncryptionKey() 
開發者ID:openstack,項目名稱:zun,代碼行數:15,代碼來源:crypt.py

示例9: decrypt

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def decrypt(token, *, context, ttl=None):
    key = retrieve_key(label=b'crypt', context=context)
    try:
        value = Fernet(key=key).decrypt(token, ttl=ttl)
        metrics.get('desecapi_key_decryption_success').labels(context).inc()
        return value
    except InvalidToken:
        raise ValueError 
開發者ID:desec-io,項目名稱:desec-stack,代碼行數:10,代碼來源:crypto.py

示例10: extract_data

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def extract_data(self, req):
        message_id = req['path_kwargs'].get('message_id')
        try:
            notif = WebPushNotification.from_message_id(
                bytes(message_id),
                fernet=self.context['conf'].fernet,
            )
        except (InvalidToken, InvalidTokenException):
            raise InvalidRequest("Invalid message ID",
                                 status_code=400)
        return dict(notification=notif) 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:13,代碼來源:message.py

示例11: extract_subscription

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def extract_subscription(self, d):
        try:
            result = self.context["conf"].parse_endpoint(
                self.context["metrics"],
                token=d["token"],
                version=d["api_ver"],
                ckey_header=d["ckey_header"],
                auth_header=d["auth_header"],
            )
        except (VapidAuthException):
            raise InvalidRequest("missing authorization header",
                                 status_code=401, errno=109)
        except (InvalidTokenException, InvalidToken):
            raise InvalidRequest("invalid token", status_code=404, errno=102)
        return result 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:17,代碼來源:webpush.py

示例12: test_delete_token_invalid

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def test_delete_token_invalid(self):
        self.fernet_mock.configure_mock(**{
            "decrypt.side_effect": InvalidToken})
        resp = yield self.client.delete(self.url(message_id='%20'))
        assert resp.get_status() == 400 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:7,代碼來源:test_endpoint.py

示例13: test_invalid_endpoint

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def test_invalid_endpoint(self):
        def err(*args, **kwargs):
            raise InvalidToken("You are unworthy")

        cli = self._makeFUT([
            "--router_tablename=fred",
            "http://something/wpush/v1/indecipherable_token"])
        cli._conf = Mock()
        cli._conf.parse_endpoint.side_effect = err
        returncode = cli.run()
        assert returncode == "Invalid Token" 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:13,代碼來源:test_diagnostic_cli.py

示例14: run

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def run(self):
        match = PUSH_RE.search(self._endpoint)
        if not match:
            return "Not a valid endpoint"

        md = match.groupdict()
        api_ver, token = md.get("api_ver", "v1"), md["token"]

        try:
            parsed = self._conf.parse_endpoint(
                self.db.metrics,
                token=token,
                version=api_ver,
            )
            uaid, chid = parsed["uaid"], parsed["chid"]
        except (InvalidTokenException, InvalidToken) as ex:
            print(("Token could not be deciphered: {}. "
                   "Are you using the correct configuration or platform?")
                  .format(ex))
            return "Invalid Token"

        print("UAID: {}\nCHID: {}\n".format(uaid, chid))

        try:
            rec = self.db.router.get_uaid(uaid)
            print("Router record:")
            self._pp.pprint(rec)
            if "current_month" in rec:
                chans = Message(rec["current_month"],
                                boto_resource=self.db.resource).all_channels(
                    uaid)
                print("Channels in message table:")
                self._pp.pprint(chans)
        except ItemNotFound as ex:
            print("Item Missing from database: {}".format(ex))
            return "Not Found"
        print("\n") 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:39,代碼來源:diagnostic_cli.py

示例15: post

# 需要導入模塊: from cryptography import fernet [as 別名]
# 或者: from cryptography.fernet import InvalidToken [as 別名]
def post(self):
        request_data = request.data
        password = request_data.pop('password', '')
        content = request_data.pop('content', '')
        if not password or not content:
            return HTTP.BAD_REQUEST(message="params required.")
        ec = Encrypt(password, current_app.config['SECRET_KEY_SALT'])
        try:
            return HTTP.OK(data=ec.decrypt(content))
        except InvalidToken:
            return HTTP.BAD_REQUEST(message="password is not correct") 
開發者ID:honmaple,項目名稱:maple-blog,代碼行數:13,代碼來源:encrypt.py


注:本文中的cryptography.fernet.InvalidToken方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。