def encrypt(msg):
'''Encrypt message with random key.
:param msg: message to be encrypted
:returns: encrypted msg and key to decrypt
'''
password = fernet.Fernet.generate_key()
f = fernet.Fernet(password)
key = f.encrypt(encodeutils.safe_encode(msg))
return encodeutils.safe_decode(password), encodeutils.safe_decode(key)
python类Fernet()的实例源码
def decrypt(msg, key):
'''Decrypt message using provided key.
:param msg: encrypted message
:param key: key used to decrypt
:returns: decrypted message string
'''
f = fernet.Fernet(encodeutils.safe_encode(msg))
msg = f.decrypt(encodeutils.safe_encode(key))
return encodeutils.safe_decode(msg)
def decrypt(cmd, message, args):
key = cmd.bot.cfg.pref.raw.get('key_to_my_heart')
text = False
if key:
if args:
if args[-1] == ':t':
text = True
crypt_text = ''.join(args[:-1]).encode('utf-8')
else:
crypt_text = ''.join(args).encode('utf-8')
key = key.encode('utf-8')
cipher = Fernet(key)
try:
ciphered = cipher.decrypt(crypt_text).decode('utf-8')
except InvalidToken:
ciphered = None
except InvalidSignature:
ciphered = None
if ciphered:
if text:
response = ciphered
else:
response = discord.Embed(color=0xe75a70)
response.add_field(name=f'?? Token Decrypted', value=ciphered)
else:
response = discord.Embed(color=0xBE1931, title='? The token or key are incorrect.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing to decrypt.')
else:
response = discord.Embed(color=0xBE1931, title='? You don\'t posses a key.')
if text:
await message.channel.send(response)
else:
await message.channel.send(embed=response)
def encrypt(cmd, message, args):
key = cmd.bot.cfg.pref.raw.get('key_to_my_heart')
text = False
if key:
if args:
if args[-1] == ':t':
text = True
crypt_text = ' '.join(args[:-1]).encode('utf-8')
else:
crypt_text = ' '.join(args).encode('utf-8')
key = key.encode('utf-8')
cipher = Fernet(key)
try:
ciphered = cipher.encrypt(crypt_text).decode('utf-8')
except InvalidToken:
ciphered = None
except InvalidSignature:
ciphered = None
if ciphered:
if text:
response = ciphered
else:
response = discord.Embed(color=0xe75a70)
response.add_field(name=f'?? Text Encrypted', value=ciphered)
else:
response = discord.Embed(color=0xBE1931, title='? The token or key are incorrect.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing to decrypt.')
else:
response = discord.Embed(color=0xBE1931, title='? You don\'t posses a key.')
if text:
await message.channel.send(response)
else:
await message.channel.send(embed=response)
def get_config(config_filename=get_default_config_filename(), secrets_file='/secrets'):
config = ConfigParser()
logger.debug('config filename: {}'.format(config_filename))
secrets = _load_secrets(filename=secrets_file)
if secrets:
from cryptography.fernet import Fernet
f = Fernet(secrets['encryption_key'].encode())
with open(config_filename, 'rb') as cfg:
cfg_content = f.decrypt(cfg.read())
print(cfg_content)
config.read_string(cfg_content.decode("utf-8") )
else:
config.read(config_filename)
expand_env_vars(config)
return config
def encrypt(message, key):
key = base64.urlsafe_b64encode(codecs.decode(key, 'hex'))
f = Fernet(key)
return f.encrypt(message.encode('utf-8')).decode('utf-8')
def decrypt(encrypted_message, key):
key = base64.urlsafe_b64encode(codecs.decode(key, 'hex'))
f = Fernet(key)
return f.decrypt(encrypted_message.encode('utf-8')).decode('utf-8')
def __init__(self, file_path, config_dict=None, encryption_key=None, binary_mode=False, *args, **kwargs):
self.config = {
'file_path': file_path,
'is_binary': None,
'is_encrypted': False,
'is_case_sensitive': None,
'is_disabled': None,
'mtime': -1,
'sha1_checksum': None,
'content': None,
'content_length': None,
}
self.is_resolved = False
self.is_file_not_found = None
self.path = Path(file_path)
self.stat = None
self.encryption_key = None
self.is_encryptable = False
self.binary_mode = False
self.config_file_type = None
self.config_dict = None
if isinstance(config_dict, dict):
self.config_dict = check_config(config_dict)
try:
self.stat = self.path.resolve().stat()
except:
self.stat = None
self.is_resolved = False
self.binary_mode = bool(binary_mode)
if encryption_key is not None:
key_len = 32
if not isinstance(encryption_key, str):
raise LocalConfigFileError('Encryption key must be a url-safe 32 character ascii string.')
if len(encryption_key[:key_len]) != key_len:
raise LocalConfigFileError('Encryption key must be a url-safe 32 character ascii string.')
self.encryption_key = base64.b64encode(encryption_key.encode('ascii'))
Fernet(self.encryption_key) # try it out, if no exception, we're good
self.is_encryptable = True
def make_fernet(self, key):
"""
Given a single encryption key, returns a Fernet instance using it.
"""
from cryptography.fernet import Fernet
if isinstance(key, six.text_type):
key = key.encode("utf8")
formatted_key = base64.urlsafe_b64encode(hashlib.sha256(key).digest())
return Fernet(formatted_key)
def save_temporary_config(temp_file_path, output_path, fernet_key=None):
with open(temp_file_path, 'rb') as fp:
file_data = fp.read()
if fernet_key:
f = Fernet(fernet_key.encode('utf-8'))
file_data = f.encrypt(file_data)
with open(output_path, 'wb') as fp:
fp.write(file_data)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self.config.salt,
iterations=100000,
backend=default_backend()
)
self.f = Fernet(base64.urlsafe_b64encode(kdf.derive(self.config.secret_key)))
def cipher(self):
return Fernet(self.key)
def decrypt(cmd, message, args):
key = cmd.bot.cfg.pref.raw.get('key_to_my_heart')
text = False
if key:
if args:
if args[-1] == ':t':
text = True
crypt_text = ''.join(args[:-1]).encode('utf-8')
else:
crypt_text = ''.join(args).encode('utf-8')
key = key.encode('utf-8')
cipher = Fernet(key)
try:
ciphered = cipher.decrypt(crypt_text).decode('utf-8')
except InvalidToken:
ciphered = None
except InvalidSignature:
ciphered = None
if ciphered:
if text:
response = ciphered
else:
response = discord.Embed(color=0xe75a70)
response.add_field(name=f'?? Token Decrypted', value=ciphered)
else:
response = discord.Embed(color=0xBE1931, title='? The token or key are incorrect.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing to decrypt.')
else:
response = discord.Embed(color=0xBE1931, title='? You don\'t posses a key.')
if text:
await message.channel.send(response)
else:
await message.channel.send(embed=response)
def encrypt(cmd, message, args):
key = cmd.bot.cfg.pref.raw.get('key_to_my_heart')
text = False
if key:
if args:
if args[-1] == ':t':
text = True
crypt_text = ' '.join(args[:-1]).encode('utf-8')
else:
crypt_text = ' '.join(args).encode('utf-8')
key = key.encode('utf-8')
cipher = Fernet(key)
try:
ciphered = cipher.encrypt(crypt_text).decode('utf-8')
except InvalidToken:
ciphered = None
except InvalidSignature:
ciphered = None
if ciphered:
if text:
response = ciphered
else:
response = discord.Embed(color=0xe75a70)
response.add_field(name=f'?? Text Encrypted', value=ciphered)
else:
response = discord.Embed(color=0xBE1931, title='? The token or key are incorrect.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing to decrypt.')
else:
response = discord.Embed(color=0xBE1931, title='? You don\'t posses a key.')
if text:
await message.channel.send(response)
else:
await message.channel.send(embed=response)
def getEncryptor(password):
if not isinstance(password, bytes):
password = bytes(password.encode())
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=SALT,
iterations=100000,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password))
return Fernet(key)
def _initialize_engine(self, parent_class_key):
self.secret_key = base64.urlsafe_b64encode(parent_class_key)
self.fernet = Fernet(self.secret_key)
def initialization(self, key):
key = base64.urlsafe_b64decode(key)
key = base64.urlsafe_b64encode(key[:32])
self._cipher = Fernet(key)
def make_fernet(self, key):
"""
Given a single encryption key, returns a Fernet instance using it.
"""
from cryptography.fernet import Fernet
key = key.encode('utf8')
formatted_key = base64.urlsafe_b64encode(hashlib.sha256(key).digest())
return Fernet(formatted_key)
def calculate_digest(secret, message, salt):
"""Calculate a SHA-256 HMAC digest for the given data."""
assert isinstance(secret, bytes), "%r is not a byte string." % (secret,)
assert isinstance(message, bytes), "%r is not byte string." % (message,)
assert isinstance(salt, bytes), "%r is not a byte string." % (salt,)
hmacr = HMAC(secret, digestmod=sha256)
hmacr.update(message)
hmacr.update(salt)
return hmacr.digest()
# Cache the Fernet pre-shared key, since it's expensive to derive the key.
# Note: this will need to change to become a dictionary if salts are supported.
def _get_or_create_fernet_psk():
"""Gets or creates a pre-shared key to be used with the Fernet algorithm.
The pre-shared key is cached in a global to prevent the expense of
recalculating it.
Uses the MAAS secret (typically /var/lib/maas/secret) to derive the key.
:return: A pre-shared key suitable for use with the Fernet class.
"""
with _fernet_lock:
global _fernet_psk
if _fernet_psk is None:
secret = get_shared_secret_from_filesystem()
if secret is None:
raise MissingSharedSecret("MAAS shared secret not found.")
# Keying material is required by PBKDF2 to be a byte string.
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
# XXX: It might be better to use the maas_id for the salt.
# But that requires the maas_id to be known in advance by all
# parties to the encrypted communication. The format of the
# cached pre-shared key would also need to change.
salt=b"",
# XXX: an infrequently-changing variable iteration count might
# be nice, but that would require protocol support, and
# changing the way the PSK is cached.
iterations=DEFAULT_ITERATION_COUNT,
backend=default_backend()
)
key = kdf.derive(secret)
key = urlsafe_b64encode(key)
_fernet_psk = key
else:
key = _fernet_psk
return key