python decode fernet key
cryptography, python
Solution
Try your code without base64 encoding your key ie:
from cryptography.fernet import Fernet as frt
key=frt.generate_key()
s = "message"
print('input string: {0}'.format(s))
#key=base64.b64encode(key) #no need to do this
print('key: {0}, type: {1}'.format(key, type(key)))
f=frt(key)
token = f.encrypt(s.encode('utf-8')) #need to convert the string to bytes
print ('encrypted: {0}'.format(token))
output = f.decrypt(token)
output_decoded = output.decode('utf-8')
print ('decrypted: {0}'.format(output_decoded))
Problem
I have generated few fernet keys and stored in str format for reference. Now, I need to encode these fernet keys in str format to 32 url-safe base64-encoded bytes to decrypt my data. ``` from cryptography.fernet import Fernet as frt keys=set() keybin='keys' keybin=open(keybin,'w') for i in range(r.randint(5,14)): key=frt.generate_key() keys.add(key.decode()) for k in keys: keybin.write(str(k)) keybin.write('\n') ``` I'm using below code to access the file and decrypt `s` ``` key=linecache.getline(cfile,x).encode() key=base64.b64encode(key) print(key) f=frt(key) token =f.decrypt(s.encode()) ``` But is giving me the below error: ``` "Fernet key must be 32 url-safe base64-encoded bytes." ValueError: Fernet key must be 32 url-safe base64-encoded bytes. ```