本文整理匯總了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)
示例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
示例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
示例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)
示例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)
示例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
示例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()
示例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()
示例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
示例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)
示例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
示例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
示例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"
示例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")
示例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")