AttributeError: 'bytes' object has no attribute 'encrypt_at_time' in MultiFernet

890 Views Asked by At

Just Trying to Encrypt the plain text using MultiFernet.

My code is:

from cryptography.fernet import Fernet, MultiFernet

fetnet_keys = [
      Fernet.generate_key(), 
      Fernet.generate_key()
]    
mulfern = MultiFernet(fetnet_keys)
enc = mulfern.encrypt("My Message in Plain Text".encode('utf-8'))

print(enc)

When trying to encrypt the plain text I am getting:

Traceback (most recent call last):
  File "encryption1.py", line 21, in <module>
    enc = mulfern.encrypt("My Message in Plain Text".encode('utf-8'))
  File "venv3.8\lib\site-packages\cryptography\fernet.py", line 169, in encrypt
    return self.encrypt_at_time(msg, int(time.time()))
  File "venv3.8\lib\site-packages\cryptography\fernet.py", line 172, in encrypt_at_time
    return self._fernets[0].encrypt_at_time(msg, current_time)
AttributeError: 'bytes' object has no attribute 'encrypt_at_time'

What's the solution?

1

There are 1 best solutions below

1
On

Fernet.generate_key() returns a bytes object. That key should be used to initialize a Fernet object. MultiFernet() takes a list of Fernet objects. Note MultiFernet encrypts with the first key in the list, but decrypts by trying each key.

Example:

from cryptography.fernet import Fernet, MultiFernet, InvalidToken

old_key = Fernet(Fernet.generate_key())
new_key = Fernet(Fernet.generate_key())

mulfern = MultiFernet([new_key, old_key])

old_enc = old_key.encrypt(b'old message')
print(old_enc)
new_enc = mulfern.encrypt(b'My Message in Plain Text')
print(new_enc)

try:
    print(old_key.decrypt(new_enc))
except InvalidToken:
    print('old_key failed')
print(mulfern.decrypt(old_enc))
print(mulfern.decrypt(new_enc))

Output:

b'gAAAAABgo0EvjyAPIc3jHHYBc8iTppwENHPO16S_suoaq3u3UzXUuTcxEmvFr62ZEvw53lPJ9MDYO2A5Ys2dPP77B61jHYbrFQ=='
b'gAAAAABgo0Ev8a4Ixt6HHGVJ8Udkr1gJfjmcfg-Wd96NOR8lrpkhS7USVrZj0WiF74druiZHiDhXxxSt1Wb2CURHYdlZ8-o0SEcEhfOzEl66qgVX2pyNP6Y='
old_key failed
b'old message'
b'My Message in Plain Text'