title: Encrypting a file with RSA in Python
body: <p>I'm implementing file encryption with RSA, using PyCrypto.</p>
  
  <p>I know it's somewhat wrong, first of all because RSA is very slow and second because PyCrypto RSA can only encrypt 128 characters, so you have to explode the file in 128 characters chunks.</p>
  
  <p>This is the code so far:</p>
  
  <pre><code>from Crypto.PublicKey import RSA
  
  file_to_encrypt = open('my_file.ext', 'rb').read()
  pub_key = open('my_pub_key.pem', 'rb').read()
  o = RSA.importKey(pub_key)
  
  to_join = []
  step = 0
  
  while 1:
      # Read 128 characters at a time.
      s = file_to_encrypt[step*128:(step+1)*128]
      if not s: break
      # Encrypt with RSA and append the result to list.
      # RSA encryption returns a tuple containing 1 string, so i fetch the string.
      to_join.append(o.encrypt(s, 0)[0])
      step += 1
  
  # Join the results.
  # I hope the \r\r\r sequence won't appear in the encrypted result,
  # when i explode the string back for decryption.
  encrypted = '\r\r\r'.join(to_join)
  # Write the encrypted file.
  open('encrypted_file.ext', 'wb').write(encrypted)
  </code></pre>
  
  <p>So my question is : are there any better methods for using Private/ Public key encryption ON FILES ?</p>
  
  <p>I heard about Mcrypt and OpenSSL, but I don't know if they can encrypt files.</p>