pythonfernet

"Fernet" python encoding gives me the following error: ValueError: Fernet key must be 32 url-safe base64-encoded bytes


I have the following code that takes the encrypted keys from a .bin file

from cryptography.fernet import Fernet
    def C(i):
      f=open('/home/credentials.bin',"rb")
      e=f.read()
      e=e.split("\n")
      e2=e[-2]
      d = Fernet(e2)
      c = e[i]
      t = (d.decrypt(c))
      s= bytes(t).decode("utf-8")
      f.close()
      return str(s)
    
    print(C(0))

trying to print the decrypted key gives me the following error:

"Fernet key must be 32 url-safe base64-encoded bytes."

ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

credentials.bin continent `

"gAAAAABeTAKV_odfhx3i6BhiaXeEDdxvG3eDdployKspvIcnm87zXd94fklNm1mMVkTlN6UUehyw0VzgNU1mj0Zlzi6yNynmOA=="

`

I appreciate your help


Solution

  • Your key is too long for a Fernet key: it is:

    len("gAAAAABeTAKV_odfhx3i6BhiaXeEDdxvG3eDdployKspvIcnm87zXd94fklNm1mMVkTlN6UUehyw0VzgNU1mj0Zlzi6yNynmOA==")
    

    output:

    100
    

    whereas fernet keys are:

    len(Fernet.generate_key())
    

    output:

    44
    

    The only way it works with your key is if you cut off the first part but I am pretty sure this is not how it was intended

    Fernet("gAAAAABeTAKV_odfhx3i6BhiaXeEDdxvG3eDdployKspvIcnm87zXd94fklNm1mMVkTlN6UUehyw0VzgNU1mj0Zlzi6yNynmOA=="[-45:-1])
    

    output:

    <cryptography.fernet.Fernet object at 0x7feb65b5bf10>
    

    I think you have the wrong key here, or it is not a Fernet key.