title: How to Encrypt a PDF in python using pycryptodome
body: <p>I am trying to encrypt a PDF file using <a href="https://www.pycryptodome.org/en/latest/" rel="nofollow noreferrer">PyCryptodome</a> and giving some unique ID of the system as key parameter. i.e uuid etc. I want to use <em>AES Encryption</em> along with GCM mode because GCM mode is an <em>Authentic Encryption</em>, as it returns a MAC that is used for authentication. I have following troubles:</p>
  
  <ol>
  <li>I have googled a lot, but can't find a code that encrypts a file. Everybody is encrypting strings.</li>
  <li>I want to use GCM mode with AES, so, need an example that uses GCM mode.</li>
  <li>In the example given below, after encrypting code is appending <code>iv</code> (Initialization Vector) with the encrypted text and using it while decryption. So my question is, how will I accomplish this while encrypting files.</li>
  <li>I don't know how to use the MAC authenticity check while decrypting the file.</li>
  </ol>
  
  <p>This is what I have with me right now, It is also encrypting string, unfortunately:</p>
  
  <pre><code>import base64
  import hashlib
  from Cryptodome.Cipher import AES
  from Cryptodome.Random import get_random_bytes
  
  key = hashlib.sha256(b"uuid goes here").digest()
  
  def encrypt(raw):
      BS = AES.block_size
      pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
      raw = base64.b64encode(pad(raw).encode('utf8'))
      iv = get_random_bytes(AES.block_size)
      cipher = AES.new(key= key, mode= AES.MODE_CFB,iv= iv)
      return base64.b64encode(iv + cipher.encrypt(raw))
  
  def decrypt(enc):
      unpad = lambda s: s[:-ord(s[-1:])]
      enc = base64.b64decode(enc)
      iv = enc[:AES.block_size]
      cipher = AES.new(key, AES.MODE_CFB, iv)
      return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))
  
  
  e = encrypt('I am string, dont you want to use file?')
  print(decrypt(e))
  </code></pre>