Skip to content

Instantly share code, notes, and snippets.

@deepal
Created October 28, 2015 22:31
Show Gist options
  • Save deepal/a084c0563dddf8497321 to your computer and use it in GitHub Desktop.
Save deepal/a084c0563dddf8497321 to your computer and use it in GitHub Desktop.
def encrypt(filepath):
print "[!] Starting Encryption...."
aes_key = os.urandom(32)
out_filename = filepath + ".enc"
filehash = hashlib.md5(open(filepath).read()).hexdigest()
public_key_loc = PUB_KEY_LOC
pubkey = open(public_key_loc, "r").read()
rsakey = RSA.importKey(pubkey)
rsakey = PKCS1_OAEP.new(rsakey)
encKey = rsakey.encrypt(aes_key)
outFile = open(out_filename,"w+")
outFile.write(filehash)
outFile.write(encKey)
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor = AES.new(aes_key, AES.MODE_CBC, iv)
filesize = os.path.getsize(filepath)
chunksize=64*1024
with open(filepath, 'rb') as infile:
outFile.write(struct.pack('<Q', filesize))
outFile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outFile.write(encryptor.encrypt(chunk))
outFile.close()
print "[+] Encryption successful!"
return out_filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment