title: I am trying to read a string encrypt it save it to a text file then read the text file read the encrypted string decrypt it in python
body: <p>I am trying to read a string encrypt it save it to a text file then read the text file read the encrypted string decrypt it in python, I am using cryptography library, I think the error is because of python lists adding [&quot;string&quot;] at the beginning and at the end,i also tried converting the read list into binary but it takes it as b[&quot;b'key'&quot;],any ideas</p>
  <pre><code>def write_key():                                #creating a key
      key = Fernet.generate_key()
      with open(&quot;key.key&quot;, &quot;wb&quot;) as key_file:
          key_file.write(key)
  
  def load_key():                                 #reading the generated key
      return open(&quot;key.key&quot;, &quot;rb&quot;).read()
  
  data = input()
  data = bytes(data,'utf-8')                      #you cannot encrypt str do converting it to bytes
  write_key()                                     #creating the key
  key = load_key()                                #loading the key
  f = Fernet(key)
  encrypted = f.encrypt(data)                     #encrypting the data
  print(encrypted)
  
  file = open(&quot;encrypted.txt&quot;, &quot;w&quot;)               #writing the encrypted the data       
  file.write(&quot;%s\n&quot; %(encrypted))
  file.close()
  
  with open(&quot;encrypted.txt&quot;, &quot;r&quot;) as f:           #reading the encrypted the data
      rdata = [line.rstrip('\n') for line in f]    #removing \n as it is added while saving the txt file
  print(rdata)
  
  
  key = load_key()
  f = Fernet(key)
  decrypted_encrypted = f.decrypt(rdata)
  print(decrypted_encrypted)
  </code></pre>
  <p>Output i get:</p>
  <pre><code>Enter the secret message: YOUR MESSAGE
  Printing the encrypted message after encryption b'gAAAAABfWdNG64dvT-tpQA1EA-zYC8lsC4hL9EoZ0e008BMIWikfafT_FOmLyjWJh2dinGG8oi6VI16XCpwB1H4AZE2sk-ZgJQ=='
  Printing the encrypted message after reading it from the txt file [&quot;b'gAAAAABfWdNG64dvT-tpQA1EA-zYC8lsC4hL9EoZ0e008BMIWikfafT_FOmLyjWJh2dinGG8oi6VI16XCpwB1H4AZE2sk-ZgJQ=='&quot;]
  Traceback (most recent call last):
  
    File &quot;C:\Users\Documents\Projects\temp.py&quot;, line 31, in &lt;module&gt;
      decrypted_encrypted = f.decrypt(rdata)
  
    File &quot;C:\Users\anaconda3\lib\site-packages\cryptography\fernet.py&quot;, line 74, in decrypt
      timestamp, data = Fernet._get_unverified_token_data(token)
  
    File &quot;C:\Users\anaconda3\lib\site-packages\cryptography\fernet.py&quot;, line 85, in _get_unverified_token_data
      utils._check_bytes(&quot;token&quot;, token)
  
    File &quot;C:\Users\anaconda3\lib\site-packages\cryptography\utils.py&quot;, line 31, in _check_bytes
      raise TypeError(&quot;{} must be bytes&quot;.format(name))
  
  TypeError: token must be bytes
  </code></pre>