def save_to_file(self, file_name="password_file.pswd"): """Save the file to disk after encrypting it. Args: file_name (str): path to created file """ with open(file_name, "wb") as file: pickle.dump(self, file) encrypt_file(file_name, load_key(self.master_key))
def send_file(self, file_info): """ send file from client to server """ # verify if this file exist (same name in this directory) dir_key = "/" # FIXME set where is.... need more discussion file_obj = file.File(name=file_info.relative_filepath, user_id=self.user_id, num_parts=3) #make list of server ip (without uid) be a circular list server_cycle = cycle([item[1] for item in self.primary_server]) #Use variable primary_server -> [ [uid,ip], [uid,ip] ... ] server_conn = self.rpc.set_server(next(server_cycle)) # ask to server if is update or new file salt = server_conn.get_salt( file_obj.name, file_obj.user_id) read_key = file_obj.set_keys(self.configs.loaded_config.get("User", "private key"), salt) crypto.encrypt_file(read_key, file_info.absolute_filepath, file_info.absolute_enc_filepath, 16) # verify if exist file if not ( misc.split_file(file_info.absolute_enc_filepath, file_obj.num_parts) ): sys.exit("Problems while splitting file.\nTry again.") # if salt has a value then is update. because server return a valid salt if salt: for num_part in range( file_obj.num_parts ): port_server = server_conn.update_file( file_obj, num_part ) print("enviando o arquivo para ", self.rpc.ip_server, " parte ", num_part) if port_server == False: sys.exit("Some error occurred. Maybe you don't have permission to \ write. \nTry again.") self.send_file_part( num_part, self.rpc.ip_server, port_server, file_info.absolute_enc_filepath ) server_conn = self.rpc.set_server(next(server_cycle)) else: # server return port where will wait a file for num_part in range(file_obj.num_parts): port_server = server_conn.negotiate_store_part(file_obj, dir_key, num_part) if not port_server: sys.exit("Some error occurred. Maybe you don't have permission to write. \nTry again.") print("[sem salt] enviando o arquivo para ", self.rpc.ip_server, " parte ", num_part) self.send_file_part(num_part, self.rpc.ip_server, port_server, file_info.absolute_enc_filepath) server_conn = self.rpc.set_server(next(server_cycle)) # remove temp crypt file os.remove(file_info.absolute_enc_filepath)
def encrypt(self, file): if self.dest is None: print( "\nRecuerde introducir el id del destinatario con --dest_id\n") return print('\nEstá en el sistema como ' + self.user.user_short()) # Leer fichero mes = open(file, 'rb').read() # Obtener clave publica del destinatario public_key = RSA.import_key( securebox.getPublicKey(self.user, self.dest)) # Cifraamos el fichero con dicha clave enc = crypto.encrypt_file(mes, public_key) # Escribimos el fichero cifrado en otro con mismo nombre, acabado en .enc filename = file.split('/')[-1] name = 'Archivos/' + filename + '.enc' r = open(name, 'wb') r.write(enc) r.close() print('\nFichero cifrado guardado en ' + name)
def sql_add(con, file): """ Functie ce adauga in baza de date metadatele despre fisierul file si creeaza in folderul de encryption un folder in care se afla mesajul criptat al acestui file. In baza de date se introduc: nume, tip_fisier, size, metoda_criptare si key_for_decryption. :param con: conexiunea la baza de data curenta :param file: path-ul fisierului ce trebuie adaugat :return: None- daca verificarile au trecut cu succes, fisierul nou a fost adaugat cu succes """ cursorObj = con.cursor() name = additional.file_name(file) if not name: print("Invalid PATH or FILE! Please try again!") return fileName, fileType = name.split('.') filePath = exists_row(fileName) if not filePath: print("Exista deja acest fisier!") else: params = (fileName, fileType, filePath, 'RSA', str(additional.getCurrentPrivateKey()), str(additional.getSize(file))) try: cursorObj.execute( "INSERT INTO encryptedDatabase VALUES(?,?,?,?,?,?)", params) con.commit() print(f"Fisierul {fileName} a fost inserat cu succes!") try: finalPath = \ cursorObj.execute("SELECT encryptedPath from encryptedDatabase WHERE fileName = ?", (fileName,)).fetchone()[ 0] crypto.encrypt_file(file, finalPath) except Error: print(Error) except Error: print(Error)
def extract_thumbnail(video_file): segment_name = os.path.basename(video_file).replace('.ts', '') thumbnail_filename = os.path.join(VIDEO_OUTPUT_PATH, segment_name + '.jpg') unencrypted_thumbnail_filename = os.path.join( VIDEO_OUTPUT_PATH, segment_name + '.unencrypted.jpg') playlist_filename = os.path.join(VIDEO_OUTPUT_PATH, segment_name + '.m3u8') playlist = """\ #EXTM3U #EXT-X-VERSION:3 #EXT-X-TARGETDURATION:3 #EXT-X-MEDIA-SEQUENCE:1 #EXT-X-KEY:METHOD=AES-128,URI="{key_file}" #EXTINF:3, {segment_file} #EXT-X-ENDLIST """.format(key_file=SYMMETRIC_KEY_FILE_PATH, segment_file=video_file) with open(playlist_filename, 'w') as playlist_file: playlist_file.write(playlist) if not os.path.isfile(unencrypted_thumbnail_filename): cmd = 'ffmpeg' + \ ' -allowed_extensions ALL' + \ ' -i ' + shlex.quote(playlist_filename) + \ ' -vframes 1 -q:v 2 ' + unencrypted_thumbnail_filename process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) process.wait() if not os.path.isfile(thumbnail_filename): encrypt_file(SYMMETRIC_KEY_FILE_PATH, unencrypted_thumbnail_filename, thumbnail_filename) os.remove(unencrypted_thumbnail_filename) os.remove(playlist_filename) return thumbnail_filename
parser.add_argument('-d', '--decrypt', dest='decrypt', help='Decrypt mode', default=False, action='store_true') parser.add_argument('-i', '--input', dest='input', type=str, help='The input file (or folder)', default='') parser.add_argument('-o', '--output', dest='output', type=str, help='The output file (or folder, optional)', default='') parser.add_argument('-p', '--password', dest='password', type=str, help='The password of the file', default='') args = parser.parse_args() if not args.input or (not args.decrypt and not args.encrypt): print("Invalid arguments.") exit(0) if args.password: password = args.password else: password = getpass() if args.encrypt: if args.output: print(crypto.encrypt_file(args.input, args.output, password)) else: print(crypto.encrypt(args.input, password)) elif args.decrypt: if args.output: print(crypto.decrypt_file(args.input, args.output, password)) else: print(crypto.decrypt(args.input, password)) else: print("Invalid arguments.")
import os import sys import crypto def fail_exit(): print('Usage: python edcrypt.py -e(encrypt)/-d(decrypt) filename password') raise SystemExit(1) # check command line args are valid if len(sys.argv) != 4: fail_exit() if not os.path.isfile(sys.argv[2]): print('File ' + sys.argv[2] + ' does not exist.') raise SystemExit(1) # parse command line args if sys.argv[1] == '-e': crypto.encrypt_file(sys.argv[3].encode(), sys.argv[2]) elif sys.argv[1] == '-d': crypto.decrypt_file(sys.argv[3].encode(), sys.argv[2]) else: fail_exit()
def on_enc_cilck(self): output = encrypt_file(self.textbox.text(), self.label.text()) QMessageBox.information(self, "加密成功", "加密成功! 加密文件路径: " + output, QMessageBox.Close)
import crypto import argparse # encrypt a value in the DEFAULT section args = argparse.Namespace(option='test') myVar = crypto.encrypt_value(args) # encrypt a value in mysection and set a value args = argparse.Namespace(section='mysection', option='myvalue', value='myvalue') myVar = crypto.encrypt_value(args) # encrypt a value in mysection and set a value args = argparse.Namespace(section='mysection', option='myvalue') myVar = crypto.decrypt_value(args) print(myVar) # Encrypt a file my_secret_file.txt with a key prefix of dev args = argparse.Namespace(file='my_secret_file.txt', key=dev) myVar = crypto.encrypt_file(args) # Set an unencrypted value in the configuration file crypto.set_value_config('url', b'htps://...', '') # Retreive the unencrypted value enc_data = crypto.get_value_config('url') print(enc_data)
# encrypt.py # Main code to encrypt a plaintext file. from crypto import encrypt_file BLOCK_SIZE = 16 e = 0 # replace by e from the recipient's public key n = 0 # replace by n from the recipient's public key encrypt_file("decrypted2.txt", "ciphertext.txt", e, n, BLOCK_SIZE, None)
def main(options): for attempt in (1,2,3): try: passphrase = getpass.getpass('Enter the passphrase to decrypt %s: ' % (options.filename,)) cleartext = decrypt_file(passphrase, filename=options.filename) break except GPGOperationFailed, error: if 'DECRYPTION_FAILED' in error.status: print("Wrong password; try again.") else: print("Unknown error; %s" % (error,)) else: print("Wrong passphrase.") return FAILURE if options.view: vim.view(cleartext) return SUCCESS temporary_filename = utils.get_temporary_filename('visafe') try: vim.edit(cleartext, output_filename=temporary_filename) except vim.TextUnchanged: return SUCCESS utils.remove_with_backup(options.filename) encrypt_file(passphrase, source_filename=temporary_filename, destintation_filename=options.filename) os.remove(temporary_filename) return SUCCESS
decrypted = crypto.decrypt_RSA(encrypted, private_key) if text == decrypted: print("Cifrado RSA exitoso\n") else: print("Cifrado RSA fallido\n") # Test de cifrado de fichero f = 'ideas' file = open(f, 'r') content = file.read() file.close() encrypted = crypto.encrypt_file(f, public_key) decrypted = crypto.decrypt_file(encrypted, private_key) if content == decrypted: print("Cifrado fichero exitoso\n") else: print("Cifrado fichero fallido\n") # Test de firma digital signature = crypto.digital_signature(text, private_key) if crypto.verify_signature(text, public_key, signature): print("Firma digital verificada\n") else: print("Firma digital rechazada\n")