0

我正在使用盐变量进行 ferney 加密。第一次生成后,salt 将转换为字符串以存储在 JSON 文件中,然后我需要将其重新转换为字节以用于解密。

但在控制台中,这是我所拥有的:

encrypt key:  b'eMA0pdSgH4Jz_DObdAL5QYdnCzJryze7gySHIx4V6Zw='
salt token:  1492684EDD7C538D23AFAB1AB179B67E
encrypt salt:  b'\x14\x92hN\xdd|S\x8d#\xaf\xab\x1a\xb1y\xb6~'
decrypt key:  b'sHH65A1nwJ0HB0j_K8ieFmMI2TNhk-CGeYxpB6VGCEo='
decrypt salt:  b'1492684EDD7C538D23AFAB1AB179B67E'

密钥不一样,加解密的盐也不一样。我认为这是盐编码/解码的问题,因为加密/解密盐不一样。

我哪里错了?

def encrypt_data(data_enc,discord_identifier, password):
password = password.encode()
with open('data/DB.json') as json_file: 

    data = json.load(json_file) 
  
    try:
        temp = data[discord_identifier] 
        find = 1
    except KeyError:
        print("ID doesn't exist")
        find = 0

if find == 1:
    salt_token = data[discord_identifier][0]['salt']
    salt = base64.b16decode(salt_token)

if find == 0:
    salt = os.urandom(16)
    salt_token = base64.b16encode(salt).decode('utf-8')
    data[discord_identifier] = [ 
        {
            'salt': salt_token
        }
    ]
    json.dump(data, open('data/DB.json', "w"), indent = 4)


kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(password))
print('encrypt key: ',key)
print('salt token: ', salt_token)
print('encrypt salt: ', salt)

f = Fernet(key)
return f.encrypt(data_enc.encode())

这是解密函数:

def decrypt_json(discord_identifier, password):
global API_key
global secret_key
global discord_id
global exchange

password = password.encode()
with open('data/DB.json') as json_file: 

    data = json.load(json_file) 
  
    try:
        salt = bytes(data[discord_identifier][0]['salt'], encoding='utf8')
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=100000,
        )
        key = base64.urlsafe_b64encode(kdf.derive(password))
        print("decrypt key: ", key)
        print('decrypt salt: ', salt)
        f = Fernet(key)
        API_key = bytes(data[discord_identifier][0]['api_key'], encoding='utf8')
        print(API_key)
        print(type(API_key))
        API_key = f.decrypt(API_key)
        
        #API_key = f.decrypt(bytes(data[discord_identifier][0]['api_key'], encoding='utf8'))
        secret_key = f.decrypt(bytes(data[discord_identifier][0]['secret_key'], encoding='utf8'))
        print(API_key)
        print(secret_key)

    except KeyError:
        print("ID doesn't exist")
4

0 回答 0