I am trying to encrypt a PDF file using PyCryptodome and giving some unique ID of the system as key parameter. i.e uuid etc. I want to use AES Encryption along with GCM mode because GCM mode is an Authentic Encryption, as it returns a MAC that is used for authentication. I have following troubles:
- I have googled a lot, but can't find a code that encrypts a file. Everybody is encrypting strings.
- I want to use GCM mode with AES, so, need an example that uses GCM mode.
- In the example given below, after encrypting code is appending
iv
(Initialization Vector) with the encrypted text and using it while decryption. So my question is, how will I accomplish this while encrypting files. - I don't know how to use the MAC authenticity check while decrypting the file.
This is what I have with me right now, It is also encrypting string, unfortunately:
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))