def encrypt(self): password = self.password with open(self.new_file, "rb") as fIn: with open(self.new_file + ".txt.aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, self.buffersize) print("done") remove(self.new_file)
def encrypt_data(self, msg): data = msg.encode('utf-8') fIn = io.BytesIO(data) fCiph = io.BytesIO() pyAesCrypt.encryptStream(fIn, fCiph, self.password, self.bufferSize) message = fCiph.getvalue() return message
def test_fl_quick(self): # encrypt with open(filenames[4], "rb") as fIn: with open(encfilenames[4], "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) # decrypt # with open(encfilenames[4], "rb") as fIn: with DecryptingReader(encfilenames[4], password) as fIn: with open(decfilenames[4], "wb") as fOut: for chunk in iter(lambda: fIn.read(10), b''): fOut.write(chunk) # check that the original file and the output file are equal self.assertTrue(filecmp.cmp(filenames[4], decfilenames[4])) fIn = DecryptingReader(encfilenames[4], password) with open(decfilenames[4], "wb") as fOut: fOut.write(fIn.read()) # check that the original file and the output file are equal self.assertTrue(filecmp.cmp(filenames[4], decfilenames[4])) # Test seek to mid-file fIn = DecryptingReader(encfilenames[4], password) fIn.seek(10) with open(decfilenames[4], "wb") as fOut: fOut.write(fIn.read()) with open(filenames[4], 'rb') as fExpected: fExpected.seek(10) expected = fExpected.read() self.assertEqual(expected, open(decfilenames[4], 'rb').read())
def save_user_secrets(user_id, secret_dict, passphrase): secret_dir = os.path.expanduser('~/.pan_cnc') try: if not os.path.isdir(secret_dir): os.mkdir(secret_dir, mode=0o700) file_path = os.path.join(secret_dir, user_id) pickled_data = pickle.dumps(secret_dict) buffer_size = 64 * 1024 # input plaintext binary stream secret_input_stream = io.BytesIO(pickled_data) # initialize ciphertext binary stream secret_output_stream = io.BytesIO() # encrypt stream pyAesCrypt.encryptStream(secret_input_stream, secret_output_stream, passphrase, buffer_size) secret_output_stream.seek(0) with open(file_path, 'wb+') as fps: fps.write(secret_output_stream.getvalue()) except OSError: print('Caught Error saving user secrets!') return False except BaseException: print('Caught Error saving user secrets!') return False return True
def _project_key(project_name): password_encryption_key = os.environ[ DataEncryptionHandler. CRYPTO_PASS] if DataEncryptionHandler.CRYPTO_PASS in os.environ else None if password_encryption_key is None: raise TVBException("Password encryption key is not defined.") project_keys_folder = os.path.join(TvbProfile.current.TVB_STORAGE, DataEncryptionHandler.KEYS_FOLDER) DataEncryptionHandler.file_helper.check_created(project_keys_folder) encrypted_project_key = DataEncryptionHandler.project_key_path( project_name) if os.path.exists(encrypted_project_key): with open(encrypted_project_key, "rb") as fIn: inputFileSize = stat(encrypted_project_key).st_size pass_stream = BytesIO() pyAesCrypt.decryptStream(fIn, pass_stream, password_encryption_key, 64 * 1024, inputFileSize) project_key = pass_stream.getvalue().decode() pass_stream.close() return project_key project_key = EncryptionHandler.generate_random_password(64) with open(encrypted_project_key, "wb") as fOut: pass_stream = BytesIO(str.encode(project_key)) pyAesCrypt.encryptStream(pass_stream, fOut, password_encryption_key, 64 * 1024) pass_stream.close() return project_key
def encrypt(password, filename): print("[+] Encrypting...") path = filename with open(path, "rb") as orig: with open(path + ".aes", "wb") as orig_enc: pyAesCrypt.encryptStream(orig, orig_enc, password, buffer_size) secure_wipe(path)
def encrypt(self): password = input("password: "******"rb") as fIn: with open("test.txt.aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, self.buffersize) print("done") remove(self.file)
def encryptFile(): with open(file_to_encrypt, "rb") as fIn: with open(file_to_decrypt, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) fOut.close() fIn.close() os.remove(file_to_encrypt)
def encrypt(self): #method to encrypt the file try: if (self.verify()): filename = self.filebox.get().split('/')[-1] #compress the file with open(self.filebox.get(), 'rb') as f_in, gz.open(filename + '.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) #encrypt the compressed file with open(filename + ".gz", 'rb') as fIn, open( self.savebox.get() + "/" + filename + ".aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, self.passbox.get(), 64 * 1024) #remove the temporary compressed file remove(filename + ".gz") self.err.set("Encryption Successfull") #display the message #clear the input boxes self.filebox.delete(0, tk.END) self.savebox.delete(0, tk.END) except FileNotFoundError: self.err.set("Invalid File or save location") finally: self.passbox.delete(0, tk.END) self.verifypassbox.delete(0, tk.END)
def encrypt(path, key): print("> encrypting ", path) # encrypt with open(path, "rb") as fIn: with open(path + ".crp0", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, str(key), bufferSize) print(">", path, " encrypted!")
def encrypt_file(self, in_filename): if Utils.password == "": return bufferSize = 64 * 1024 password = Utils.password # binary data to be encrypted pbdata = open(in_filename, 'rb').read() # input plaintext binary stream fIn = io.BytesIO(pbdata) # initialize ciphertext binary stream fCiph = io.BytesIO() # initialize decrypted binary stream fDec = io.BytesIO() # encrypt stream pyAesCrypt.encryptStream(fIn, fCiph, password, bufferSize) # print encrypted data print("This is the ciphertext:\n" + str(fCiph.getvalue())) l = open(in_filename, 'wb') l.write(fCiph.getvalue()) l.close()
def sign_up(request): if request.method == 'POST': myfile = '' firmname = request.POST['firmname'] firmhead = request.POST['firmhead'] addr = request.POST['address'] # addr=request.POST['addr'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] myfile = request.FILES['doc'] print(myfile.name, 'myfile') fn = myfile.name ext = fn[-4:] print(ext, 'ext') extension = ext # curr_path = str(request.user.id) + '/application' curr_path = "/" + email + "/registration/" curr_path = curr_path.replace('/', '\\') new_path = os.path.join(settings.MEDIA_ROOT + curr_path) print(new_path, 'newpath') fs = FileSystemStorage(location=new_path, base_url=new_path) # encrypt the file # fs = FileSystemStorage() unique_filename = str(uuid.uuid4()) filename = fs.save(unique_filename, myfile) uploaded_file_url = fs.path(filename) print(uploaded_file_url, 'url') bufferSize = 64 * 1024 passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e" with open(uploaded_file_url, "rb") as fIn: with open(uploaded_file_url + ".aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, passw, bufferSize) date_joined = datetime.now() formatted_datetime = date_joined.strftime("%Y-%m-%d") status = 'inactive' reg = registration(firmname=firmname, firmhead=firmhead, addr=addr, username=username, email=email, password=password, doc=uploaded_file_url + ".aes", status=status, remarks='', extension=extension, request_date=formatted_datetime) reg.save() # send_mail('New Firm Registration', 'Hi admin, Kindly register the new user '+username, '*****@*****.**', ['*****@*****.**',]) remove(uploaded_file_url) messages.success(request, 'Firm Registration UnderProcess!!!') return redirect('enroll')
def addanotherdoc(request): idnew=request.POST['idnew'] refpath=request.POST['refp'] idprefix=request.POST['idprefix'] fcat=request.POST['fcat'] refdate=request.POST['refd'] file_refno=request.POST['refn'] files = request.FILES['updoc'] tafcount=TAapplicationfiles.objects.filter(user_id=request.user.id,filecategory=fcat,refid=idprefix).count() refpathcount = str(refpath[9:])+'.'+str(tafcount) newrefpath='Annexure '+str(refpathcount) ann_ex=TAapplicationfiles.objects.filter(refpath=newrefpath,user_id=request.user.id).exists() if ann_ex: form=fileUploadForm taf=TAapplicationfiles.objects.filter(user_id=request.user.id).order_by('refpath') idg=idgenerationmodel.objects.filter(user_id=request.user.id,idprefix=idprefix).first() print(idnew,refpath,fcat,refpathcount,'nnnnnnnnnnnnnnnnnn') return render(request, 'applicant/view_all_doc.html',{'form':form,'details': taf,'idg':idg,'idprefix':idprefix}) else: newpath=refpath+'/'+fcat+'/'+newrefpath print(files.name,'myfile') fn=files.name ext=fn[-4:] print(ext,'ext') extension=ext curr_path = "/"+str(request.user.id)+ "/"+idprefix+newpath+"/" curr_path=curr_path.replace('/','\\') new_path = os.path.join(settings.MEDIA_ROOT + curr_path) print(new_path,'newpath') fs = FileSystemStorage(location=new_path , base_url = new_path ) # unique_filename = str(uuid.uuid4()) # filename = fs.save(unique_filename, files) filename = fs.save(files.name, files) uploaded_file_url = fs.path(filename) print(uploaded_file_url,'url') bufferSize = 64 * 1024 passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e" with open(uploaded_file_url, "rb") as fIn: with open(uploaded_file_url+".aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, passw, bufferSize) # refpath=idprefix+newpath+ "/"+files.name remove(uploaded_file_url) taf = TAapplicationfiles(filecategory=fcat, filepath=uploaded_file_url+".aes",ext=extension,user_id=request.user.id,refid=idprefix,refpath=newrefpath,refdate=refdate,file_refno=file_refno,relation='child') taff=taf.save() form=fileUploadForm taf=TAapplicationfiles.objects.filter(user_id=request.user.id).order_by('refpath') idg=idgenerationmodel.objects.filter(user_id=request.user.id,idprefix=idprefix).first() print(idnew,refpath,fcat,refpathcount,'nnnnnnnnnnnnnnnnnn') return render(request, 'applicant/view_all_doc.html',{'form':form,'details': taf,'idg':idg,'idprefix':idprefix})
def EncryptFunc(entry): # convert the string into a byte stream pbdata = bytes(entry, encoding='utf-8') fIn = io.BytesIO(pbdata) pyAesCrypt.encryptStream(fIn, fCiph, password, bufferSize) # print encrypted data print("This is the ciphertext:\n" + str(fCiph.getvalue())) return fCiph.getvalue()
def encrypt(self, plaintext: bytes) -> bytes: ciphertext_stream = io.BytesIO() pyAesCrypt.encryptStream( io.BytesIO(plaintext), ciphertext_stream, self.password, self._BUFFER_SIZE ) return ciphertext_stream.getvalue()
def aes_enc(inputFile, outputFile, password): with open(inputFile, "rb") as fIn: with open(outputFile, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) fIn.close() #steganographed image removed for security purpose after usage remove(inputFile)
def encrypt(text: str) -> bytes: passwd = h.VMConfig.get(1)['aes_key'] bufferSize = 128 * 1024 text_bin = text.encode('utf-8') text_file = BytesIO(text_bin) result_file = BytesIO() pyAesCrypt.encryptStream(text_file, result_file, passwd, bufferSize) return result_file.getvalue()
def cipher_stream(inp_buffer: BytesIO, password: str): """Ciphers an input memory buffer and returns a ciphered output memory buffer""" # Initialize output ciphered binary stream out_buffer = BytesIO() inp_buffer.seek(0) # Encrypt Stream pyAesCrypt.encryptStream(inp_buffer, out_buffer, password, BUFFER_SIZE) out_buffer.seek(0) return out_buffer
def toCrypt(file, output, password, bufferSize=64 * 1024): # print(password) filename = file.split('\\')[-1] outputFile = output+'\\'+filename+'.crypted' # print(output) with open(file, 'rb') as fIn: with open(outputFile, 'wb') as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) return outputFile
def encryptFile(dictData, filepath): myjson = json.dumps(dictData) myBytejson = myjson.encode('utf8') # input plaintext binary stream fIn = io.BytesIO(myBytejson) with open(filepath, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) cksum = md5(filepath) return cksum
def encrypt(pbdata, password): bufferSize = 64 * 1024 # input plaintext binary stream fIn = BytesIO(pbdata) # initialize ciphertext binary stream fCiph = BytesIO() # encrypt stream pyAesCrypt.encryptStream(fIn, fCiph, password, bufferSize) return fCiph.getvalue()
def _encrypt_data(self, data, service): """ Encrypts """ file_path = self.get_path_for(service) data_to_encrypt = json.dumps(data).encode('utf-8') stream_to_encrypt = io.BytesIO(data_to_encrypt) with open(file_path, 'wb') as file: pyAesCrypt.encryptStream(stream_to_encrypt, file, self.password, self.bufferSize) file.close()
def encrypt_AesCrypt(file, key): """ """ # encryption/decryption buffer size - 128K bufferSize = 128 * 1024 save_name = file.path + ".aes" # encrypt with open(str(file.path), "rb") as fIn: with open(save_name, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, key, bufferSize) remove(file.path)
def ProcessInsertData(): global noofdb, secretkey, sdata noofdb = 2 sdata = request.form['sdata'] if len(sdata.strip()) < noofdb: return render_template('CreateDatabase.html', processResult='Invalid Input Data') connection = pypyodbc.connect( 'Driver={SQL Server};Server=WISEN\\SQLEXPRESS;Integrated_Security=true;', autocommit=True) cursor = connection.cursor() domain = sdata data = textwrap.wrap(domain, math.ceil(len(domain) / noofdb)) for index in range(noofdb): conn1 = pypyodbc.connect( 'Driver={SQL Server};Server=WISEN\\SQLEXPRESS;Integrated_Security=true;Database=db' + str(index + 1), autocommit=True) cur1 = conn1.cursor() if cur1.tables(table='MyTable', tableType='TABLE').fetchone(): bufferSize = 64 * 1024 password = "******" # binary data to be encrypted pbdata = b"data[index] \x00\x01" # input plaintext binary stream fIn = io.BytesIO(pbdata) # initialize ciphertext binary stream fCiph = io.BytesIO() # initialize decrypted binary stream fDec = io.BytesIO() # encrypt stream pyAesCrypt.encryptStream(fIn, fCiph, password, bufferSize) print(str(fCiph.getvalue())) sdata = str(fCiph.getvalue()).replace("'", "''") sqlcmd1 = "INSERT INTO MyTable (SecretData) VALUES('" + sdata + "')" print(sqlcmd1) cur1.execute(sqlcmd1) cur1.commit() pass conn1.close() connection.close() return render_template('InsertData.html', processResult="Done. Data are Stored. ")
def encryptZipfile(zipfile, backupname): # encryption/decryption buffer size - 64K bufferSize = 64 * 1024 password = keyring.get_password("PC-Backups", "backupGdrive") # encrypt with open(zipfile, "rb") as fIn: with open(backupname, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) os.remove(zipfile)
def encryptZipfileLocal(zipfile, backupname, dest): # encryption/decryption buffer size - 64K bufferSize = 64 * 1024 password = keyring.get_password("PC-Backups", "backupGdrive") finaldest = dest + "/" + backupname # encrypt with open(zipfile, "rb") as fIn: with open(finaldest, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) print("Backup taken on {}".format(datetime.now())) os.remove(zipfile)
def encripto(self, from_, to_): bufferSize = 64 * 1024 password = input('Введите пароль для генерации ключа шифрования: ') if password == '': password = random.randint(1385, 9732) print('Ваш сгенерированный пароль: ', password) print('Запишите его! Иначе не сможете расшифровать файл') with open(from_, "rb") as fIn: with open(to_, "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) print('Success')
def get(): file_name = Entrye1.get() password = Entrye2.get() image_name = Entrye3.get() print(file_name) print(password) print(image_name) t_file_name1 = os.path.basename(file_name) t_file_name = '' n1 = len(t_file_name1) for i in range(n1 - 4): t_file_name = t_file_name + t_file_name1[i] print(t_file_name1) print(t_file_name) save_image(image_name) # encrypt with open(file_name, "rb") as fIn: with open(file_name + ".aes", "wb") as fOut: pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize) os.chmod(file_name, S_IWRITE) shutil.copy2(file_name + '.aes', 'Data/') os.remove(file_name) # get encrypted file size encFileSize = stat(file_name + ".aes").st_size encFileSize = str(encFileSize) #print(encFileSize) passcodes = '' #print(t_file_name) with open('Data/' + t_file_name + '.txt', 'w+') as f: f.writelines(file_name) f.writelines('*') f.writelines(password) f.writelines('#') f.writelines(encFileSize) with open('Data/' + t_file_name + '.txt', 'r+') as f: passcodes = f.readlines() #print(passcodes) temp_encrypt = "" for i in passcodes[0]: ow = ord(i) nw = ow + key i = chr(nw) temp_encrypt = temp_encrypt + i print(temp_encrypt) temp_encrypt = listToString(temp_encrypt) with open('Data/' + t_file_name + '.txt', 'w+') as f: f.writelines(temp_encrypt) shutil.copy2('Data/' + t_file_name1 + '.aes', 'UI_Data/Backup/') shutil.copy2('Data/' + t_file_name + '.txt', 'UI_Data/Backup/') main_menu1()
def encrypt_string(plaintext: str, password: str) -> str: plaintext_stream = io.BytesIO(plaintext.encode()) ciphertext_stream = io.BytesIO() pyAesCrypt.encryptStream(plaintext_stream, ciphertext_stream, password, BUFFER_SIZE) ciphertext_b64 = base64.b64encode(ciphertext_stream.getvalue()) logger.info("String encrypted.") return ciphertext_b64.decode()
def saveWallet(self, priv, name, password, overwrite=False): import os fCiph = io.BytesIO() fin = io.BytesIO(priv) if os.path.isfile("./wallets_cipher/" + remove_special_char(name[:20]) + ".wallet.dat") == False or overwrite == True: with open( "./wallets_cipher/" + remove_special_char(name[:20]) + ".wallet.dat", 'wb') as outfile: pyAesCrypt.encryptStream(fin, fCiph, password, self.bufferSize) outfile.write(fCiph.getvalue())