如何使用自己的密钥进行加密?
我已经在网上搜索过这样做。如何使用自己的密钥进行加密?在 python 中,我更喜欢
密码学。它不断弹出错误Fernet key must be 32 url-safe base64-encoded bytes
和TypeError: a bytes-like object is required, not 'str'
. 我正在尝试创建一个私有变量函数。我是python新手。
这是我未完成的代码。谢谢您的帮助。
from cryptography.fernet import Fernet
import inspect
import hashlib
import base64 #Fernet key must be 32 url-safe base64-encoded bytes
def encode(key, string):
encoded_chars = []
for i in xrange(len(string)):
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
encoded_chars.append(encoded_c)
encoded_string = "".join(encoded_chars)
return base64.urlsafe_b64encode(encoded_string)
class private:
class sec_storage:
data = dict()
hashed_data = dict()
class var:
def create(var,value):
# creates key based on caller
key = hashlib.sha224(str(inspect.stack()).encode()).hexdigest()
cipher_suite = Fernet(base64.b64encode(key)) #Fernet key must be 32 url-safe base64-encoded bytes
# encrypts using key
encoded_text = cipher_suite.encrypt(value)
# prepares storage
hashed_var = hashlib.sha224("plus".join(list(var.encode(),key[:12])).hexdigest())
hashed_value = hashlib.sha224(value.encode()).hexdigest()[12:30]
private.sec_storage.data[hashed_var] = encoded_text
private.sec_storage.hashed_data[hashed_var] = hashed_value
def read(var):
# creates key based on caller
key = hashlib.sha224(str(inspect.stack()).encode()).hexdigest()
cipher_suite = Fernet(base64.b64encode(key)) #Fernet key must be 32 url-safe base64-encoded bytes
# retrieve var
hashed_varname = hashlib.sha224("plus".join(list(var.encode(),key[:12])).hexdigest())
try:
hashed_var = private.sec_storage.data[hashed_varname]
except NameError:
raise NameError("Requested variable not found")
# decrypts using key
decoded_text = cipher_suite.decrypt(hashed_var)
hashed_value = hashlib.sha224(decoded_text.encode()).hexdigest()[12:30]
# checks if password is correct
if private.sec_storage.hashed_data[hashed_varname] != hashed_value:
raise ValueError("Value not as requested")
return decoded_text
private.var.create("myvar","Hello World!")
print(private.var.read("myvar"))
print(sec_storage.data)
如你看到的cipher_suite = Fernet(base64.b64encode(key)) #Fernet key must be 32 url-safe base64-encoded
我如何解决它?