本文整理汇总了Python中cryptography.fernet.MultiFernet.decrypt方法的典型用法代码示例。如果您正苦于以下问题:Python MultiFernet.decrypt方法的具体用法?Python MultiFernet.decrypt怎么用?Python MultiFernet.decrypt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.fernet.MultiFernet
的用法示例。
在下文中一共展示了MultiFernet.decrypt方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_decrypt
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
def test_decrypt(self, backend):
f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
f = MultiFernet([f1, f2])
assert f.decrypt(f1.encrypt(b"abc")) == b"abc"
assert f.decrypt(f2.encrypt(b"abc")) == b"abc"
with pytest.raises(InvalidToken):
f.decrypt(b"\x00" * 16)
示例2: test_rotate
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
def test_rotate(self, backend):
f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
mf1 = MultiFernet([f1])
mf2 = MultiFernet([f2, f1])
plaintext = b"abc"
mf1_ciphertext = mf1.encrypt(plaintext)
assert mf2.decrypt(mf1_ciphertext) == plaintext
rotated = mf2.rotate(mf1_ciphertext)
assert rotated != mf1_ciphertext
assert mf2.decrypt(rotated) == plaintext
with pytest.raises(InvalidToken):
mf1.decrypt(rotated)
示例3: EncryptingPacker
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
class EncryptingPacker(object):
"""Implement conversion of Python objects to/from encrypted bytestrings.
:param str key: a `Fernet`_ key to use for encryption and decryption
:param list old_keys: additional `Fernet`_ keys to use for decryption
.. note::
Encrypted messages contain the timestamp at which they were generated
*in plaintext*. See `our audit`_ for discussion of this and other
considerations with `Fernet`_.
.. _Fernet: https://cryptography.io/en/latest/fernet/
.. _our audit: https://github.com/gratipay/gratipay.com/pull/3998#issuecomment-216227070
"""
def __init__(self, key, *old_keys):
keys = [key] + list(old_keys)
self.fernet = MultiFernet([Fernet(k) for k in keys])
def pack(self, obj):
"""Given a JSON-serializable object, return a `Fernet`_ token.
"""
obj = json.dumps(obj) # serialize to unicode
obj = obj.encode('utf8') # convert to bytes
obj = self.fernet.encrypt(obj) # encrypt
return obj
def unpack(self, token):
"""Given a `Fernet`_ token with JSON in the ciphertext, return a Python object.
"""
obj = token
if not type(obj) is bytes:
raise TypeError("need bytes, got {}".format(type(obj)))
obj = self.fernet.decrypt(obj) # decrypt
obj = obj.decode('utf8') # convert to unicode
obj = json.loads(obj) # deserialize from unicode
return obj
示例4: AutopushSettings
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
#.........这里部分代码省略.........
# Both tables found, safe to switch-over
self.current_month = today.month
self.current_msg_month = message_table.table_name
self.message_tables[self.current_msg_month] = \
Message(message_table, self.metrics)
returnValue(True)
def update(self, **kwargs):
"""Update the arguments, if a ``crypto_key`` is in kwargs then the
``self.fernet`` attribute will be initialized"""
for key, val in kwargs.items():
if key == "crypto_key":
fkeys = []
if not isinstance(val, list):
val = [val]
for v in val:
fkeys.append(Fernet(v))
self.fernet = MultiFernet(fkeys)
else:
setattr(self, key, val)
def make_simplepush_endpoint(self, uaid, chid):
"""Create a simplepush endpoint"""
root = self.endpoint_url + "/spush/"
base = (uaid.replace('-', '').decode("hex") +
chid.replace('-', '').decode("hex"))
return root + 'v1/' + self.fernet.encrypt(base).strip('=')
def make_endpoint(self, uaid, chid, key=None):
"""Create an v1 or v2 WebPush endpoint from the identifiers.
Both endpoints use bytes instead of hex to reduce ID length.
v0 is uaid.hex + ':' + chid.hex and is deprecated.
v1 is the uaid + chid
v2 is the uaid + chid + sha256(key).bytes
:param uaid: User Agent Identifier
:param chid: Channel or Subscription ID
:param key: Optional Base64 URL-encoded application server key
:returns: Push endpoint
"""
root = self.endpoint_url + '/push/'
base = (uaid.replace('-', '').decode("hex") +
chid.replace('-', '').decode("hex"))
if key is None:
return root + 'v1/' + self.fernet.encrypt(base).strip('=')
raw_key = base64url_decode(key.encode('utf8'))
ep = self.fernet.encrypt(base + sha256(raw_key).digest()).strip('=')
return root + 'v2/' + ep
def parse_endpoint(self, token, version="v0", ckey_header=None):
"""Parse an endpoint into component elements of UAID, CHID and optional
key hash if v2
:param token: The obscured subscription data.
:param version: This is the API version of the token.
:param ckey_header: the Crypto-Key header bearing the public key
(from Crypto-Key: p256ecdsa=)
:raises ValueError: In the case of a malformed endpoint.
:returns: a dict containing (uaid=UAID, chid=CHID, public_key=KEY)
"""
token = self.fernet.decrypt(repad(token).encode('utf8'))
public_key = None
if ckey_header:
try:
crypto_key = CryptoKey(ckey_header)
except CryptoKeyException:
raise InvalidTokenException("Invalid key data")
label = crypto_key.get_label('p256ecdsa')
try:
public_key = base64url_decode(label)
except:
# Ignore missing and malformed app server keys.
pass
if version == 'v0':
if not VALID_V0_TOKEN.match(token):
raise InvalidTokenException("Corrupted push token")
items = token.split(':')
return dict(uaid=items[0], chid=items[1], public_key=public_key)
if version == 'v1' and len(token) != 32:
raise InvalidTokenException("Corrupted push token")
if version == 'v2':
if len(token) != 64:
raise InvalidTokenException("Corrupted push token")
if not public_key:
raise InvalidTokenException("Invalid key data")
if not constant_time.bytes_eq(sha256(public_key).digest(),
token[32:]):
raise InvalidTokenException("Key mismatch")
return dict(uaid=token[:16].encode('hex'),
chid=token[16:32].encode('hex'),
public_key=public_key)
示例5: RedisChannelLayer
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
#.........这里部分代码省略.........
pass
def _group_key(self, group):
return ("%s:group:%s" % (self.prefix, group)).encode("utf8")
def _channel_groups_key(self, group):
return ("%s:chgroups:%s" % (self.prefix, group)).encode("utf8")
### Flush extension ###
def flush(self):
"""
Deletes all messages and groups on all shards.
"""
for connection in self._connection_list:
self.delprefix(keys=[], args=[self.prefix+"*"], client=connection)
### Serialization ###
def serialize(self, message):
"""
Serializes message to a byte string.
"""
value = msgpack.packb(message, use_bin_type=True)
if self.crypter:
value = self.crypter.encrypt(value)
return value
def deserialize(self, message):
"""
Deserializes from a byte string.
"""
if self.crypter:
message = self.crypter.decrypt(message, self.expiry + 10)
return msgpack.unpackb(message, encoding="utf8")
### Redis Lua scripts ###
# Single-command channel send. Returns error if over capacity.
# Keys: message, channel_list
# Args: content, expiry, capacity
lua_chansend = """
if redis.call('llen', KEYS[2]) >= tonumber(ARGV[3]) then
return redis.error_reply("full")
end
redis.call('set', KEYS[1], ARGV[1])
redis.call('expire', KEYS[1], ARGV[2])
redis.call('rpush', KEYS[2], KEYS[1])
redis.call('expire', KEYS[2], ARGV[2] + 1)
"""
lua_lpopmany = """
for keyCount = 1, #KEYS do
local result = redis.call('LPOP', KEYS[keyCount])
if result then
return {KEYS[keyCount], result}
end
end
return {nil, nil}
"""
lua_delprefix = """
local keys = redis.call('keys', ARGV[1])
for i=1,#keys,5000 do
redis.call('del', unpack(keys, i, math.min(i+4999, #keys)))
end
示例6: __init__
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
class SecretStore:
def __init__(self, *master_keys, encrypted_store: dict = None):
if not len(master_keys):
raise ValueError('at least one master key must be passed')
self.crypt = MultiFernet([Fernet(key) for key in master_keys])
if not encrypted_store:
self.encrypted_store = dict()
else:
self.encrypted_store = encrypted_store
@staticmethod
def generate_master_key():
return Fernet.generate_key()
@staticmethod
def add_master_key(key_yaml_path):
master_key = SecretStore.generate_master_key()
try:
master_keys = SecretStore._load_keys(key_yaml_path)
except OSError:
master_keys = []
master_keys = [master_key] + master_keys
SecretStore._save_as_yaml(key_yaml_path, 'keys', master_keys)
return master_keys
@staticmethod
def _load_keys(key_yaml_path):
with open(key_yaml_path, 'r') as key_file:
master_keys = yaml.load(key_file)['keys']
return master_keys
@classmethod
def load_from_yaml(cls, key_yaml_path, store_yaml_path=None, encrypted=True):
master_keys = SecretStore._load_keys(key_yaml_path)
secret_store = cls(*master_keys)
if store_yaml_path:
secret_store.load_as_yaml(store_yaml_path, encrypted=encrypted)
return secret_store
def encrypt_copy(self, plain_store, *path):
for key in plain_store:
value = plain_store[key]
if isinstance(value, bytes) or isinstance(value, str):
self.set_secret(value, *path, key)
else:
self.encrypt_copy(value, *(list(path) + [key]))
def set_secret(self, secret, *path):
if not len(path):
raise ValueError('path to secret must not be empty')
if not (isinstance(secret, bytes) or isinstance(secret, str)):
raise ValueError(
'secret must be bytes or str, but {0} is passed'.format(
type(secret)))
if isinstance(secret, str):
secret = secret.encode('utf-8')
encrypted_secret = self.crypt.encrypt(secret)
store = self.encrypted_store
for key in path[:-1]:
store = store.setdefault(key, dict())
store[path[-1]] = encrypted_secret
def get_secret(self, *path):
encrypted_secret = self.get_encrypted_secret(*path)
return self.crypt.decrypt(encrypted_secret)
def delete_secret(self, *path):
if not len(path):
raise ValueError('path to secret must not be empty')
store = self.encrypted_store
for key in path[:-1]:
store = store[key]
del store[path[-1]]
def get_encrypted_secret(self, *path):
if not len(path):
raise ValueError('path to secret must not be empty')
store = self.encrypted_store
for key in path[:-1]:
store = store[key]
encrypted_secret = store[path[-1]]
return encrypted_secret
def load_as_yaml(self, yaml_path, encrypted=True):
with open(yaml_path, 'r') as secret_file:
secret_storage = yaml.load(secret_file)
if encrypted:
self.encrypted_store = secret_storage['encrypted_store']
else:
self.encrypt_copy(secret_storage['encrypted_store'])
def save_as_yaml(self, yaml_path):
SecretStore._save_as_yaml(yaml_path, 'encrypted_store', self.encrypted_store)
def print_as_yaml(self):
print(yaml.dump(self.encrypted_store, default_flow_style=False))
@staticmethod
def _wrap_payload(payload_key, payload):
now = datetime.now()
#.........这里部分代码省略.........
示例7: Cryptograph
# 需要导入模块: from cryptography.fernet import MultiFernet [as 别名]
# 或者: from cryptography.fernet.MultiFernet import decrypt [as 别名]
class Cryptograph(object):
"""Symmetric encryption and decryption for the storage of sensitive data.
We currently rely on Fernet, which was the algorithm adopted by Gratipay:
https://github.com/gratipay/gratipay.com/pull/3998#issuecomment-216227070
For encryption Fernet uses the AES cipher in CBC mode with PKCS7 padding and
a 128 bits key. For authentication it uses HMAC-SHA256 with another 128 bits
key.
Fernet messages contain the timestamp at which they were generated *in plain
text*. This isn't a problem for us since we want to store the time at which
the data was encrypted in order to facilitate key rotation.
We use CBOR (Concise Binary Object Representation) to serialize objects
before encryption. Compared to JSON, CBOR is faster to parse and serialize,
more compact, and extensible (it can represent any data type using "tags").
More info on CBOR: http://cbor.io/ https://tools.ietf.org/html/rfc7049
"""
KEY_ROTATION_DELAY = timedelta(weeks=1)
def __init__(self):
if website.env.aws_secret_access_key:
sm = self.secrets_manager = boto3.client('secretsmanager', region_name='eu-west-1')
secret = sm.get_secret_value(SecretId='Fernet')
rotation_start = secret['CreatedDate'].date()
keys = secret['SecretString'].split()
else:
self.secrets_manager = None
parts = os.environ['SECRET_FERNET_KEYS'].split()
rotation_start = date(*map(int, parts[0].split('-')))
keys = parts[1:]
self.fernet_rotation_start = rotation_start
self.fernet_keys = [k.encode('ascii') for k in keys]
self.fernet = MultiFernet([Fernet(k) for k in self.fernet_keys])
def encrypt_dict(self, dic, allow_single_key=False):
"""Serialize and encrypt a dictionary for storage in the database.
Encrypting partially predictable data may help an attacker break the
encryption key, so to make our data less predictable we randomize the
order of the dict's items before serializing it.
For this to be effective the CBOR serializer must not sort the items
again in an attempt to produce Canonical CBOR, so we explicitly pass
`canonical=False` to the `cbor.dumps` function.
In addition, the dict must not contain only one key if that key is
predictable, so a `CryptoWarning` is emitted when `dic` only contains
one key, unless `allow_single_key` is set to `True`.
"""
dic = self.randomize_dict(dic, allow_single_key=allow_single_key)
serialized = cbor.dumps(dic, canonical=False)
encrypted = self.fernet.encrypt(serialized)
return Encrypted(dict(scheme='fernet', payload=encrypted, ts=utcnow()))
def decrypt(self, scheme, payload):
"""Decrypt and reconstruct an object stored in the database.
"""
if scheme == 'fernet':
decrypted = self.fernet.decrypt(payload)
else:
raise ValueError('unknown encryption scheme %r' % scheme)
return cbor.loads(decrypted)
@staticmethod
def randomize_dict(dic, allow_single_key=False):
"""Randomize the order of a dictionary's items.
Emits a `CryptoWarning` if `dic` only contains one key, unless
`allow_single_key` is set to `True`.
"""
if not isinstance(dic, dict):
raise TypeError("expected a dict, got %s" % type(dic))
# Compute the number of random bytes needed based on the size of the dict
n = len(dic)
if n < 2:
# Can't randomize the order if the dict contains less than 2 items
if n == 1 and not allow_single_key:
warnings.warn("dict only contains one key", CryptoWarning)
return dic
n = int(log(n, 2) // 8) + 2
# Return a new ordered dict sorted randomly
return OrderedDict(
t[1] for t in sorted((urandom(n), item) for item in dic.items())
)
def rotate_key(self):
"""Generate a new key and send it to the secrets manager.
"""
keys = b' '.join([Fernet.generate_key()] + self.fernet_keys).decode()
if self.secrets_manager:
self.secrets_manager.update_secret(SecretId='Fernet', SecretString=keys)
else:
keys = utcnow().date().isoformat() + ' ' + keys
print("No secrets manager, updating the key storage is up to you.")
return keys
def rotate_message(self, msg, force=False):
#.........这里部分代码省略.........