Skip to content

Instantly share code, notes, and snippets.

@febimudiyanto
Created February 13, 2022 16:05
Show Gist options
  • Save febimudiyanto/54c52ae842dcc6f205c1d59a73ff3362 to your computer and use it in GitHub Desktop.
Save febimudiyanto/54c52ae842dcc6f205c1d59a73ff3362 to your computer and use it in GitHub Desktop.
def encrypt(dataFile, publicKeyFile):
'''
use EAX mode to allow detection of unauthorized modifications
'''
# read data from file
with open(dataFile, 'rb') as f:
data = f.read()
# convert data to bytes
data = bytes(data)
# read public key from file
with open(publicKeyFile, 'rb') as f:
publicKey = f.read()
# create public key object
key = RSA.import_key(publicKey)
sessionKey = os.urandom(16)
# encrypt the session key with the public key
cipher = PKCS1_OAEP.new(key)
encryptedSessionKey = cipher.encrypt(sessionKey)
# encrypt the data with the session key
cipher = AES.new(sessionKey, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
[]
# save the encrypted data to file
[ fileName, fileExtension ] = dataFile.split('.')
encryptedFile = fileName + '_encrypted.' + fileExtension
with open(encryptedFile, 'wb') as f:
[ f.write(x) for x in (encryptedSessionKey, cipher.nonce, tag, ciphertext) ]
print('Encrypted file saved to ' + encryptedFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment