我必须用密钥加密字符串并将加密对象存储为字符串,它必须很强,所以我决定使用提供 aes 加密“密码学”的模块https://pypi.org/project/cryptography/
如你所见,我做了一系列函数来方便使用 Fernet 加密,但是由于某种原因它不能处理反斜杠、换行符、缩进和回车,得到的解密结果与原始字符串不同,这里的测试字符串是 "t\n\t"
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
def encrypt_string(string_, password, f = None):
if f is None:
f = get_fernet_(password)
try:
return str(f.encrypt(string_.encode()))[2:- 1]
except:
return None
def decrypt_string(string_, password, f = None):
if f is None:
f = get_fernet_(password)
try:
return str(f.decrypt(string_.encode()))[2:- 1]
except:
return None
def get_fernet_(password):
if password and isinstance(password,str):
kdf = PBKDF2HMAC(algorithm = hashes.SHA256(),
length = 32,
salt = password.encode(),
iterations = 100000,
backend = default_backend())
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
f = Fernet(key)
return f
def test_encryption(s = "text", password = "key"):
my_f = get_fernet_(password)
s2 = encrypt_string(s, password)
s3 = decrypt_string(s2, password)
s4 = encrypt_string(s, password, my_f)
s5 = decrypt_string(s4, password, my_f)
if s == s3 and s == s5:
return True
return False
print (test_encryption("text"))
True
print (test_encryption("t\n\t"))
False
如果有人可以为此特定代码或可以满足我需要的不同加密算法提供解决方案
问题是您正在尝试使用文字而不是方法将bytes
对象转换为 a :string
str
bytes.decode()
from cryptography.fernet import Fernet
# Im just using a random key for simplicity
key = Fernet.generate_key()
f = Fernet(key)
mystr = 'hi\tthere'
enc = f.encrypt(mystr.encode()) # str.encode() creates a bytes object
dec = f.decrypt(enc)
str(dec)
# "b'hi\\tthere'"
# This is NOT the same, use decode
mystr==str(dec[2:-1]) # returns False
mystr==dec.decode() # returns True
dec.decode()
# 'hi\tthere'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句