def myencode_str(ori_str, key):
enc = []
for i in range(len(ori_str)):
key_c = key[i % len(key)]
enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
enc.append(enc_c)
return (base64.urlsafe_b64encode(bytes(enc))).decode("utf-8")
或者请参阅此处以获取完整示例:
from cryptography.fernet import Fernet
class Encrypt(object):
'''
see https://cryptography.io/en/latest/fernet/
'''
@classmethod
def encrypt(cls, plain_text):
'''
@param enctypted_text: str or bytes
@return cipher_text: str (.decode() converts the byte string to string)
'''
if isinstance(plain_text, str):
plain_text = plain_text.encode()
elif not isinstance(plain_text, bytes):
raise ValueError('Value must be string or bytes')
cipher_suite = Fernet(config.KEY.encode())
cipher_text = cipher_suite.encrypt(plain_text).decode()
return cipher_text
@classmethod
def decrypt(cls, enctypted_text):
'''
@param enctypted_text: str or bytes
@return plain_text: str (.decode() converts the byte string to string)
'''
if isinstance(enctypted_text, str):
enctypted_text = enctypted_text.encode()
elif not isinstance(enctypted_text, bytes):
raise ValueError('Value must be string or bytes')
cipher_suite = Fernet(config.KEY.encode())
plain_text = cipher_suite.decrypt(enctypted_text).decode()
return plain_text
@classmethod
def generateKey(cls):
key = Fernet.generate_key()
return key*