def handle_new_file(user, uploaded, bulletin_id, encryption_key=None, rand=Random.new()): if encryption_key == '': encryption_key = None r, c, ep, iv, encryption_key = create_encryption_params(encryption_key, rand) file = File( author=user, bulletin=Bulletin.objects.get(pk=bulletin_id), name=uploaded.name, content=uploaded, rand=r, check=c, encryption_params=ep, date_created=datetime.now(), date_modified=datetime.now(), ) if encryption_key is not None: with tempfile.NamedTemporaryFile() as temp: cipher = AES.new(encryption_key, AES.MODE_CFB, iv) for chunk in uploaded.chunks(): encrypted_chunk = cipher.encrypt(chunk) temp.write(encrypted_chunk) temp.seek(0) file.content = DFile(temp) file.save() give_file_access(user, user, file, encryption_key) else: file.save()