def anneal(text, key, ciphertype, keytype, keybreak): ngram = ngram_obj( "https://gist.githubusercontent.com/DomDale/9a582deed33b20bb47e0363301d2c6c4/raw/62e7416f6be95893649398f0470f1dcd2668e608/english_trigrams.txt" ) cost = ngram.cost(decrypt.decrypt(text, key, ciphertype)) temp = 1.0 tempmin = 0.0001 alpha = 0.99 # multiplication factor iters = 10 # iterations at each temperature acc = 0 while temp > tempmin: for x in range(1, iters): newkey = findneighbor(key, keytype, keybreak) newcost = ngram.cost(decrypt.decrypt(text, newkey, ciphertype)) ap = acceptprob(newcost, cost, temp) try: if ap > random.random(): key = newkey cost = newcost acc += 1 except: key = newkey cost = newcost acc += 1 temp *= alpha # slowly reduce temp print(decrypt.decrypt(text, key, ciphertype)) return (decrypt.decrypt(text, key, ciphertype))
def anneal(text, key, ciphertype, keytype, keybreak): ngram = ngram_obj("https://pastebin.com/raw/ZP7PWFdQ") cost = ngram.cost(decrypt.decrypt(text, key, ciphertype)) temp = 1.0 tempmin = 0.0001 alpha = 0.99 # multiplication factor iters = 10 # iterations at each temperature acc = 0 while temp > tempmin: for x in range(1, iters): newkey = findneighbor(key, keytype, keybreak) newcost = ngram.cost(decrypt.decrypt(text, newkey, ciphertype)) ap = acceptprob(newcost, cost, temp) try: if ap > random.random(): key = newkey cost = newcost acc += 1 except: key = newkey cost = newcost acc += 1 temp *= alpha # slowly reduce temp return (str(acc) + decrypt.decrypt(text, key, ciphertype))
def start(): while True: choise = int( input("Enter number: 1 for encode, 2 for decode, 3 for quit\n")) if choise == 1: # text = str(input("Enter text to encode")) text = "Lab 3 seti i telecommunikacii" #29 degree = int( input("Enter degree of encoding: 1 or 2 or 4 or 8: \n")) # text = open('text.txt', 'r') start = "start.bmp" new = "newImage.bmp" encrypt(text, degree, start, new, systemXernya=54, byte=8) elif choise == 2: degree = int( input("Enter degree of decoding: 1 or 2 or 4 or 8: \n")) toRead = int(input("How many symbols to read: \n")) new = "newImage.bmp" decrypt(degree, toRead, new, systemXernya=54, byte=8) elif choise == 3: break else: print("Unknown command!")
def upload_decrypt(): # Get the name of the uploaded file if request.method == 'POST': file = request.files['file'] #file_kr = request.files['filekr'] #file_kc = request.files['filekc'] #file_item = request.files['fileitem'] #feature = request.form['feature'] #print(feature) filename = file.filename #filename_kr = file_kr.filename #filename_kc = file_kc.filename #filename_item = file_item.filename #Save file file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) #file_kr.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_kr)) #file_kc.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_kc)) #file_item.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_item)) dec.decrypt(filename) #copy = e.encrypt(UPLOAD_FOLDER+"/"+filename, message) #copy.save(os.path.join(app.config['UPLOAD_FOLDER'], filename[:-4] + "_copy.png")) return render_template("decrypt.html", orig=filename, encoded=filename) # Check if the file is one of the allowed types/extensions else: return "File bad"
def main(): parser = argparse.ArgumentParser(description='Encrypt or decrypt with AES') parser.add_argument('--keysize', help='Either 128 or 256 bits.', required=True) parser.add_argument('--keyfile', help='The path of a keyfile that fits the keysize.', required=True) parser.add_argument('--inputfile', help='The file to encrypt or decrypt.', required=True) parser.add_argument('--outputfile', help='The path for the desired output file.', required=True) parser.add_argument('--mode', help='encrypt or decrypt', required=True) args = parser.parse_args() keysize = int(args.keysize) keyfile = args.keyfile inputfile = args.inputfile outputfile = args.outputfile mode = args.mode if mode == 'encrypt': e.encrypt(keysize, keyfile, inputfile, outputfile) elif mode == 'decrypt': d.decrypt(keysize, keyfile, inputfile, outputfile)
def BrowseFile_2(self): global fname fname = QFileDialog.getOpenFileName(None, 'Open file', '')[0] from decrypt import decrypt key = open('crypto.key', 'rb').read() decrypt(fname, key) Browser2.close()
def startdecryption(decimage): imgs=de.openimage(decimage) try: de.decrypt(imgs) result='Text file Saved as "NewTextFile.txt"' except Exception as ex: result='Select proper Image File' return result
def getAppointmentByToken(token): query = "SELECT * FROM appointment WHERE token = %s;" cursor = cnx.cursor() cursor.execute(query, (token, )) for (id, firstname, lastname, email, begin_date, end_date, business_id, token, done) in cursor: appointment = Appointment(id, decrypt(firstname), decrypt(lastname), decrypt(email), decrypt(begin_date), decrypt(end_date), business_id, token) cnx.commit() return appointment
def getAppointmentByBusinessId(id): query = "SELECT * FROM appointment WHERE business_id = %s;" cursor = cnx.cursor() cursor.execute(query, (id, )) appointment = [] for (id, firstname, lastname, email, begin_date, end_date, business_id, token, done) in cursor: appointment.append(Appointment(id, decrypt(firstname), decrypt(lastname), decrypt(email), decrypt(begin_date), decrypt(end_date), business_id, token)) cnx.commit() return appointment
def access(): print(chr(27) + "[2J") print("\n\n\t A d B P a s s w o r d M a n a g e r") print("\n\n\t Encrypted Files Found : ") dir_path = os.path.dirname(os.path.realpath(__file__)) for file in os.listdir(dir_path): if file.endswith(".bin"): print("\t\t--> " + file) fname = raw_input("\n Enter the File Name : ") decrypt(fname)
def getBusinessOwnerById(id): query = "SELECT * FROM business_owner WHERE id = %s;" cursor = cnx.cursor() cursor.execute(query, (id, )) business = None for (id, firstname, lastname, date_of_birth, email, phone) in cursor: del business business = Business_Owner(id, decrypt(firstname), decrypt(lastname), decrypt(date_of_birth), decrypt(email), decrypt(phone)) cnx.commit() return business
def choose(): print("What do you want to use?") print("Encryption or Decryption?") print("Encryption is 1") print("Decryption is 2") choose = int(input(">")) if choose == 1: ask() elif choose == 2: decrypt() else: print("Write the valid number") choose()
def beginEncryption(self, listFilenames, private_key, public_key): key = k.Key(private_key, public_key) self.changeButtonState(tk.DISABLED) self.changeTextBoxState(tk.DISABLED) for i in listFilenames: self.showBar(i, listFilenames.index(i), len(listFilenames)) if self.selection_value.get() == 1: e.encrypt(i, self.output_entry.get(), key) if self.selection_value.get() == 2: d.decrypt(i, self.output_entry.get(), key) self.progressText.set(self.encrypt_text.get()+"ion finished. ("+str(len(listFilenames))+"/"+str(len(listFilenames))+")") self.clearAllText() self.changeButtonState(tk.NORMAL)
def decfile(): filewin = Tk() filewin.filename = filedialog.askopenfilename( initialdir="/", title="Select file", filetypes=(("encrypted files", "*.enc"), ("all files", "*.*"))) print(filewin.filename) if (len(filewin.filename) > 0): decrypt.decrypt(filewin.filename, d, n) os.remove(filewin.filename) messagebox.showinfo("Success!", "Decryption Complete") else: messagebox.showerror("Error!", "File does not exist") filewin.destroy()
def encryption(): loop() while True: o=input(" How do you want to proceed\n (W)Encrypt text\n (S)Show encrypted text: \n") if o=='w' or o=='W': encrypt() break # tell me more function elif o=='S' or o=='s': decrypt() break #tell me more function else: print(" I can't get it") continue menu() time.sleep(10000)
def decrypt(self, encyptedFile): if len(self.key) != 0: rsaDecrypt(self.key); return decrypt(self.key, encyptedFile); else: return
def handler_one_wav(file_path): is_decryptted = True one_wav = wav_data() dest_path = os.path.join(temp_path, file_path.split("/")[-1]) + ".enc" if one_wav.read_wav(file_path): #un-decryptted encrypt(file_path, dest_path) is_decryptted = False pass else: #decryptted wav_file = os.path.join(temp_path, file_path.split("/")[-1][:-4]) decrypter = decrypt.decrypt("key") decrypter.decrypt(file_path, wav_file) one_wav = wav_data() one_wav.read_wav(wav_file) if one_wav.wav_channels != 1: return if one_wav.wav_sample_rate != 16000: return tmp_list = dest_path.split("/")[-1].split("_") task_id = tmp_list[1] azure_file_name = "_".join([tmp_list[1], tmp_list[2] ]) + "/" + dest_path.split("/")[-1] print(azure_file_name) if is_decryptted: #upload file_path print("decryptted") azure.upload(task_id, azure_file_name, file_path) else: #upload dest_path print("un-decryptted") azure.upload(task_id, azure_file_name, dest_path)
def test_point_encryption(self): m = ec.point(1,2,priv.A, priv.B, priv.prime) cipher = encrypt.encrypt(m, priv.base_point, priv.pub_raised_point) m2 = decrypt.decrypt(cipher, priv.exponent) self.assertEqual(m, m2)
def test_incorrect_input(self): try: student_rep = student.decrypt(-10, "test") self.assertIsNone(student_rep, "Votre fonction ne gére pas les entrées incorrectes") except Exception as e: self.fail("Votre fonction ne gére pas les entrées incorrectes")
def decrypt_if_not_db_file(file_name, key, extension=None): if is_funf_database(file_name): print "Already decrypted: '%s'" % file_name return True else: print("Attempting to decrypt: '%s'..." % file_name), decrypt.decrypt([file_name], key, extension) if is_funf_database(file_name): print "Success!" return True else: print "FAILED!!!!" print "File is either encrypted with another method, another key, or is not a valid sqlite3 db file." print "Keeping original file." shutil.move(decrypt.backup_file(file_name, extension), file_name) return False
def decrypt_if_not_db_file(file_name, key, extension=None): if is_funf_database(file_name): print "Already decrypted: '%s'" % file_name return True else: print ("Attempting to decrypt: '%s'..." % file_name), decrypt.decrypt([file_name], key, extension) if is_funf_database(file_name): print "Success!" os.remove(file_name+'.orig') return True else: print "FAILED!!!!" os.remove(file_name) os.remove(file_name+'.orig') return False
def dec(): ciphertext = request.form['decode_text'] key = request.form['decode_key'] plaintext = decrypt(ciphertext, key) return render_template('result.html', data = plaintext)
def on_click_decrypt(self): global ciphertext, finalText # Gets File Content password = self.password_tbox.text() encryptedFile = open(openedFilePath, 'r') ciphertext = encryptedFile.read() # Decrypts File Content plainText, time = decrypt(ciphertext, password) asciiPW = [ord(b) for b in password] A = getA(asciiPW, plainText) invA = linalg.inv(A) L_2 = matmul(invA, plainText) L2_1 = [int(a) % 127 for a in L_2] plainTextASCII = [chr(int(a)) for a in L2_1] finalText = ''.join(str(x) for x in plainTextASCII) # Notification that file has been Decrypted self.notification.setText("Decrypted: " + os.path.basename(encryptedFile.name)) encryptedFile.close() # Shows Time Taken to Decrypt self.time_label.setText(time + " seconds") self.author_label.setText("") self.password_tbox.clear()
def get_file(user, pasd, filename): if auth(user, pasd) == True: key = hashlib.sha224((user + pasd).encode()).hexdigest() key = int(key, 16) % 254 return decrypt(user, key, filename, pasd) else: return auth(user, pasd)
def handle_update(): if 'file' not in request.files: return Response(json.dumps({'error': 'missing file'}), status=400) files = request.files.getlist('file') print(files) for file in files: if file.filename == '': return Response(json.dumps({'error': 'missing file'}), status=400) file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) names = sorted([file.filename for file in files]) key = "-".join(names) data = {} for name in names: data[name] = decrypt(name) print(name, data[name]) rule = RULES[key] if rule.evaluate(data): print("State changed to " + str(rule.get_output())) else: print("State did not change.") return Response(status=200)
def decrypt_if_not_db_file(file_name, key, extension=None): if is_funf_database(file_name): print "Already decrypted: '%s'" % file_name return True else: print ("Attempting to decrypt: '%s'..." % file_name), decrypt.decrypt([file_name], key, extension) if is_funf_database(file_name): print "Success!" return True else: print "FAILED!!!!" print "File is either encrypted with another method, another key, or is not a valid sqlite3 db file." print "Keeping original file." shutil.move(decrypt.backup_file(file_name, extension), file_name) return False
def handler_one_wav(file_path): is_decryptted = True one_wav = wav_data() dest_path = os.path.join(temp_path, file_path.split("/")[-1]) + ".enc" if one_wav.read_wav(file_path): #un-decryptted encrypt(file_path, dest_path) is_decryptted = False pass else: #decryptted wav_file = os.path.join(temp_path, file_path.split("/")[-1][:-4]) decrypter = decrypt.decrypt("key") decrypter.decrypt(file_path, wav_file) one_wav = wav_data() one_wav.read_wav(wav_file) if one_wav.wav_channels != 1: return if one_wav.wav_sample_rate != 16000: return tmp_list = dest_path.split("/")[-1].split("_") task_id = tmp_list[1] azure_file_name = "_".join([tmp_list[1], tmp_list[2]]) + "/" + dest_path.split("/")[-1] print(azure_file_name) if is_decryptted: #upload file_path print("decryptted") azure.upload(task_id, azure_file_name, file_path) else: #upload dest_path print("un-decryptted") azure.upload(task_id, azure_file_name, dest_path)
def send_to_kindle(book_id, book_data_str, to_email): need_generate = True book_dir = 'data/%s' % book_id book_mobi_path = '%s/%s.mobi' % (book_dir, book_id) book_data = parse_book_data(book_data_str) # 是不是不需要新生成 if not book_data['is_sample'] and os.path.exists(book_mobi_path): with open('%s/data.txt' % book_dir) as fp: old_book_data_str = fp.read() old_book_content_md5 = old_book_data_str.split(':', 2)[0] if md5(book_data['encrypted_content']).hexdigest() == old_book_content_md5: need_generate = False logger.info('book %s need generate? : %s', book_id, need_generate) if need_generate: if not os.path.isdir(book_dir): os.mkdir(book_dir) with open('%s/data.txt' % book_dir, 'w') as fp: fp.write(md5(book_data['encrypted_content']).hexdigest() + ':' + book_data_str.encode('utf-8')) logger.info('decrypting %s', book_id) book_content_data_str = decrypt(book_data['encrypted_content']) book_content_data = json.loads(book_content_data_str) logger.info('decrypt successful for %s', book_id) book_title = book_data['title'] try: book_mobi_path = generate_book(book_id, book_title, book_content_data) except RuntimeError: book_mobi_path = None if book_mobi_path: subject = book_data.get('title', '') if to_email.endswith('@iduokan.com') else 'Convert' send_queue.enqueue(send_file_via_email, to_email, book_mobi_path, subject)
def __init__(self): self.sqlserver = db_handler.sqlserver_handler() self.log = log.my_log.instance() self.downloader = download.download() self.decrypter = decrypt.decrypt("key") self.azure = azure_util.azure_handler() for queue in configure.queue_list: self.azure.create_queue(queue)
def index(n): if n == 1: keys = generate_keys() print('Public key:', f'{keys["public_key"][0]},{keys["public_key"][1]}') print('Private key:', f'{keys["private_key"][0]},{keys["private_key"][1]}') return elif n == 2: text = input('Type in a text\n: ') print('\n') public_key = input('Paste a public key\n: ').split(',') print('\n') public_key[0] = int(public_key[0]) public_key[1] = int(public_key[1]) if len(public_key) == 2 and type(public_key[0]) == int and type( public_key[1]) == int: encrypted_codes = encrypt(text, public_key) codes_str = '' i = 0 for code in encrypted_codes: codes_str += f'{str(code)}' if i < len(encrypted_codes) - 1: codes_str += ',' i += 1 return print('Encrypted codes\n: ', codes_str) else: return print('Invalid public key!') elif n == 3: codes = input('Paste a list of codes\n: ') print('\n') private_key = input('Paste your private key\n: ').split(',') print('\n') private_key[0] = int(private_key[0]) private_key[1] = int(private_key[1]) codes_list = [] codes = codes.split(',') for code in codes: codes_list.append(int(code)) if len(private_key) == 2 and type(private_key[0]) == int and type( private_key[1]) == int: return print(decrypt(codes_list, private_key)) else: return print('Invalid private key!') elif n == 4: exit() else: print('Please select a valid action!') return
def transpos(text, colno): initkey = list(str(math.floor(1234567890 / (10**(10-colno))))) perms = list(itertools.permutations(initkey)) key = "" cost = 0 ngram = ngram_obj( "https://gist.githubusercontent.com/DomDale/9a582deed33b20bb47e0363301d2c6c4/raw/62e7416f6be95893649398f0470f1dcd2668e608/english_trigrams.txt") for x in range(len(perms)): newcost = ngram.cost(decrypt.decrypt( text, "".join((perms[x])), "transposition")) if newcost > cost: cost = newcost key = "".join((perms[x])) print(decrypt.decrypt( text, key, "transposition"))
def resetText(text_id, decryptor_id, decryptor_key_json): key = ndb.Key(model.Text, text_id) text = key.get() if not text: text = model.Text(key=key) text.content = open('texts/%s.txt' % text_id, 'rU').read() decryptor = {'id': decryptor_id, 'key':json.loads(decryptor_key_json)} text.encrypted = decrypt.decrypt(text.content, decryptor) text.put()
def main(): print("---------------------------------------------------") print("Music Encrypt - Music Based Encryption") print("Author: Mrinal Pande") print("---------------------------------------------------") if len(sys.argv) < 2: print("Invalid input \nFor Help:", sys.argv[0], "-h") elif sys.argv[1] == "-h": print("Help For Music Encrypt") print("---------------------------------------------------") print("Options Description") print("-f File to encrypt/Decrypt") print("-e Encrypt the file") print("-d Decrypt the file") print("-k Key to Encrypt") print("-o name of output file") print("\nFor encrypting a file:") print("python main.py -f <filename> -e -k <key> -o <output file name>") print("\nFor decrypting a file:") print("python main.py -f <filename> -d -k <key>") print("---------------------------------------------------") elif sys.argv[3] == "-e" and len(sys.argv) == 8: fpath = sys.argv[2] key = sys.argv[5] outfile = sys.argv[7] print("Starting Encryption...") if os.path.isfile(fpath): encrypt.encrypt(fpath, key, outfile) else: print("File not found \n") print("Invalid input\nFor Help:", sys.argv[0], "-h") elif sys.argv[3] == "-d" and len(sys.argv) == 6: print("Decryption") fpath = sys.argv[2] key = sys.argv[5] print("Starting decryption...") if os.path.isfile(fpath): decrypt.decrypt(fpath, key) else: print("File not found \n") print("Invalid input\nFor Help:", sys.argv[0], "-h") else: print("Invalid input\nFor Help:", sys.argv[0], "-h")
def decryption(cipher, key): dt = [] key = to_hex(pad(key))[0] for block in cipher: dt.append(decrypt(block, key)) final = "" for block in dt: final += to_str(block) return rmpad(final)
def DecryptIt(self, code, eng_text): eng_text.config(state="normal") eng_text.delete('1.0', 'end') code = code[:-1] result_List = decrypt.decrypt(code, MORSE_CODE_DICT) stri = "" for i in result_List: stri = stri + i + " " eng_text.insert('end', stri) eng_text.config(state="disabled")
def main(): msg = raw_input('Encrypted Text : ') for i in range(0,len(msg)): print 'Trying with key #%s' % i word = decrypt(i,msg) if(CountWords(word) > 0.2): #Assuming 20 percenteg of words print word sys.exit() print 'Sorry Could not find the type of encryption' sys.exit()
def __init__(self): self.sqlserver = db_handler.sqlserver_handler() self.log = log.my_log.instance() self.cut_audio = cut_audio.audio_cut() self.azure = azure_util.azure_handler() self.decrypter = decrypt.decrypt("key") self.BloomFilter = BloomFilter.BloomFilter(0.001,3000000) self.azure.create_queue(configure.cutted_queue) self.azure.create_blob(configure.cutted_blob) self.tag_task_list = configure.tag_task_list self.data_cnt = 0
def privmsg(self, user, channel, mesg): ##print mesg ##DECRYPT MESSAGE mesg = decrypt.decrypt(mesg) ##print mesg if self.factory.websocket: self.factory.websocket.write_message({"type": "chat", "user": user.split("!")[0], "message": mesg}) else: print ("websocket not open")
def waitAndReadFile(filePath): while not os.path.isfile(filePath): time.sleep(0.5) content = None content = json.loads(decrypt.decrypt(filePath, password)) os.remove(filePath) return content
def handleRequest(self): # request file click handler self.clearStatuses() if self.req_filename == '': self.changeStatus(1, 'choose a file to view', 'wrong') return req_data = json.dumps({ 'mode': 'DOWN', 'jwt': jwt, 'name': self.req_filename }) sock.send(req_data.encode('ascii')) self.changeStatus(1, 'sending download request', 'loader') res = None try: res = sock.recv(MAX_BYTES).decode('ascii') except socket.timeout: self.changeStatus(1, 'request timeout', 'wrong') return res_data = json.loads(res) if res_data['status'] == '200': self.changeStatus(1, 'downloading the file', 'loader') dec_key = res_data['enc_pvtkey'] file_length = int(res_data['length']) file_data = b'' while len(file_data) < file_length: file_data += sock.recv(MAX_BYTES) res = recv_except() if res == None: return res_data = json.loads(res.decode('ascii')) if res_data['status'] == '200': self.changeStatus(1, 'download completed', 'check') info_raw = { 'id': keys['username'].ljust(6, ' '), 'private key': keys['pvtkey'], 'decrypt key': dec_key } pv = decrypt.decrypt(info_raw, file_data) if type(pv) == str: self.changeStatus(1, pv, 'wrong') return req_data = json.dumps({ 'mode': 'CHAIN', 'jwt': jwt, 'name': self.req_filename, 'pv': pv }) sock.send(req_data.encode('ascii')) res = recv_except()
def post(self): payload = self.request.body data = json.loads(payload) text = ndb.Key(urlsafe=data['text_key']).get() level_key = ndb.Key(urlsafe=data['level_key']) # TODO verify input (text must exist, decryptor valid etc.) decrypted = decrypt.decrypt(text.encrypted, data['decryptor']); win = decrypt.check_result(text, decrypted) self.response.out.write( json.dumps({'win':win, 'text':decrypted})) user = users.get_current_user() if user and win: # if the user is signed in, record they passed this level self.getUserTracker().recordWin(level_key)
def getfile(self): items=self.listView.selectedIndexes() r=req.get(address+"/receive/get/"+str(items[0].row()+1),auth=creds,verify=False) filename=self.files[items[0].row()] ver=req.get(address+"/receive/verify/"+str(items[0].row()+1),auth=creds,verify=False) signature=binascii.unhexlify(ver.json()["sign"]) keycall=req.get(address+"/send/"+ver.json()["user"],auth=creds,verify=False) key=RsaPublicKey.Read(keycall.json()["key"]) if key.Verify(r.content,signature): QMessageBox.about(self,"Info","File verified to be from "+ver.json()["user"]) else: QMessageBox.about(self,"Info","Verification failed") decrypt_file(hashlib.sha256(str(creds[1])).digest(),creds[0]+"key.enc") open(filename,"w").write(decrypt(r.content,creds[0]+"key")) QMessageBox.about(self,"Info","File written to "+filename) os.remove(creds[0]+"key") os.system("gnome-open "+filename)
import utils import encrypt import decrypt words = utils.word_set letters = utils.letter_set on_loop = 0 print "Welcome to the Navajo Code Talkers Encryption / Decryption tool." while on_loop == 0: print "Enter 1 to Encrypt a message" print "Enter 2 to Decrypt a message" print "Enter 3 to Quit" while True: try: choice = int(raw_input("Your choice: ")) break except ValueError: print "That's not a valid choice. Please try again." if choice == 1: print "Time to encrypt" encrypt.encrypt(words,letters) elif choice == 2: print "Time to decrypt" decrypt.decrypt(words,letters) elif choice == 3: print "Thank you, have a nice day." sys.exit()
inp = to_hex(pad(plain)) key = to_hex(pad(key))[0] ct = [] for block in inp: ct.append(encrypt(block, key)) encrypted_text = "" for block in ct: encrypted_text += to_str(block) print("\n") print("Encrypted Text: ", encrypted_text) print("\n") print("\n-------------------- Decryption ----------------------\n") dt = [] for block in ct: dt.append(decrypt(block, key)) print() print("\n---------------------- Result ------------------------\n") final = "" for block in dt: final += to_str(block) print("Decrypted Text: ", rmpad(final))
if text_align in ['left', 'right', 'center']: classes.append('p_align_' + text_align) text = data.get('text') render_data = { 'text': text, 'classes': ' '.join(classes) } # image if content_type == 'illus': render_data['image'] = data['size']['orig']['src'] if content_type == 'headline': render_data['toc_anchor'] = add_to_table_of_contens(text) return render(content_type, render_data) if __name__ == '__main__': import json from decrypt import decrypt book_id = 'e1531222' with open('data/' + book_id + '/data.txt') as fp: file_content = fp.read() _, title, content = file_content.split(':')[:3] json_str = decrypt(content) data = json.loads(json_str) generate_book(book_id, title.decode('utf-8'), data)
# print "payload: {}".format(packet.getlayer(ICMP).payload) if packet.haslayer(ICMP) and str(packet.getlayer(ICMP).type) == "8": raw = packet.getlayer(ICMP).seq #if raw not in download: count +=1 ans.append(chr(raw)) #download.append(raw) print "Total packets recieved: {}".format(count) ans1 = [] for i in range(0,len(ans),2): ans1.append(ans[i]) text = "".join(ans1) #print "Recieved Data: " + text ans = [] for i in range(0,len(text),20): data = decrypt.decrypt(text[i:i+20]) #print "DATA: " + str(data) ans.append(data) #print "FINAL ANS: " + "".join(ans) image = Image.open(io.BytesIO("".join(ans))) image.save("testresult.png") #data = decrypt.decrypt(text) f.write("".join(ans)) f.close()
def run_decrypt(): form = DecryptionForm(request.form) if request.method == 'POST' and form.validate(): enter_key_input = form.enter_key encrypted_DNA_input = form.encrypted_DNA return render_template('decrypt_result.html', title="Decrypt", form=form, result = decrypt(enter_key_input, encrypted_DNA_input)) else: return render_template('decrypt.html', title="Decrypt", form=form)
keyMask = unpack('L', header[0x10:0x14])[0] ^ 0x43DE7C19 header[0x10:0x14] = array('B' , pack('L', keyMask)) with open(cpzFilename, 'rb') as cpz: fullHeader = array('B') fullHeader.fromfile(cpz, indexLength + 4) fullHeader[4:8] = array('B' , pack('L', indexCount)) fullHeader[0x8:0xC] = array('B' , pack('L', indexLength)) fullHeader[0x10:0x14] = array('B' , pack('L', keyMask)) keyMask = keyMask ^ 0x7BF4A539 #解密index delta = 12 - 20 decrypt(fullHeader, 0x14, indexLength + 4, delta, keyMask) #循环提取文件 i = 0 pos = 0x14 while i < indexCount: itemIndexLength = unpack('L', fullHeader[pos:pos + 4])[0] itemLength = unpack('L', fullHeader[pos + 4:pos + 8])[0] itemOffset = unpack('L', fullHeader[pos + 8:pos + 0x0C])[0] itemFilename = fullHeader[pos + 0x18:pos + itemIndexLength].tostring().strip('\0') # if itemFilename != 'config02_chip.pb3': # i += 1 # pos += itemIndexLength # continue itemKeyMask = unpack('L', fullHeader[pos + 0x14:pos + 0x18])[0]
log.error('The input file, encryption password and/or output file were not specified\n%s' % usage) sys.exit(1) try: #Encrypt a copy of the input file in_file = file(orig_bfile,'rb') enc_bfile = '%s.enc' % orig_bfile out_file = file(enc_bfile,'wb') encrypt(enc_pw,in_file,out_file) log.info('Created %s, an encrypted copy of %s' % (enc_bfile,orig_bfile)) #Decrypt and binary diff the encrypted copy against the original bfile_dec = '%s.dec' % orig_bfile in_file = file(enc_bfile,'rb') out_file = file(bfile_dec,'wb') decrypt(enc_pw,in_file,out_file) #if binary_diff(bfile_dec,orig_bfile): if binary_diff(bfile_dec,orig_bfile): log.info('Decrypted version %s, diffs successfully against original %s' % (bfile_dec,orig_bfile)) else: log.info('BAD ENCRYPTION COPY: decrypted version %s and original %s DIFFER' % (bfile_dec,orig_bfile)) log.info('Encryption job complete') except Exception, e: log.exception(e) sys.exit(1)
import encrypt import decrypt import datetime import msvcrt while True: encrypted = encrypt.encrypt(raw_input("\n\n\nEnter message to encrypt -- ")) print "\nEncrypted Message -- \n" print encrypted print "\nDecrypted Message -- \n" msg = decrypt.decrypt(encrypted, str(datetime.datetime.now())) print msg print "\n\n\nPress Enter to try once again or any other key to quit......" if ord(msvcrt.getch()) != 13: exit(0)
def __init__(self): self.log = log.my_log.instance() self.decrypter = decrypt.decrypt("key")
def __init__(self, srcFile): jsonStr = decrypt(srcFile) jsonObj = json.loads(jsonStr) super(Vault, self).__init__(jsonObj) self.mergeDwellers() self.mergeRooms()
def main(): from struct import unpack, pack from array import array from decrypt import decrypt, encrypt, decryptPs2, encryptPs2 from lzss import decode, encode import codecs from scriptgetter import ScriptGetter cpzFilename = ur"D:\eroge\明日の君と逢うために\data\pack\scriptback.cpz" newFilename = ur"D:\eroge\明日の君と逢うために\data\pack\script.cpz" relation_filename = ur"D:\data\workspace\asutame_text\etc\relation.txt" source_path = ur"D:\data\workspace\asutame_text\source" + u"\\" translated_path = ur"D:\data\workspace\asutame_text\已译" + u"\\" source_encoding = "shift-jis" translated_encoding = "gb18030" #解密文件头 with open(cpzFilename, 'rb') as cpz: header = array('B') header.fromfile(cpz, 0x18) indexCount = unpack('L', header[4:8])[0] ^ 0x5E9C4F37 header[4:8] = array('B' , pack('L', indexCount)) indexLength = unpack('L', header[0x8:0xC])[0] ^ 0xF32AED17 header[0x8:0xC] = array('B' , pack('L', indexLength)) keyMask = unpack('L', header[0x10:0x14])[0] ^ 0xDDDDDDDD header[0x10:0x14] = array('B' , pack('L', keyMask)) with open(cpzFilename, 'rb') as cpz: fullHeader = array('B') fullHeader.fromfile(cpz, indexLength + 0x14) fullHeader[4:8] = array('B' , pack('L', indexCount)) fullHeader[0x8:0xC] = array('B' , pack('L', indexLength)) fullHeader[0x10:0x14] = array('B' , pack('L', keyMask)) keyMask = keyMask ^ 0x7BF4A539 #解密index delta = 12 - 20 decrypt(fullHeader, 0x14, indexLength + 0x14, delta, keyMask) #循环提取文件 newCpzHeader = array('B', fullHeader.tostring()) newCpzContent = array('B') i = 0 pos = 0x14 while i < indexCount: itemIndexLength = unpack('L', fullHeader[pos:pos + 4])[0] itemLength = unpack('L', fullHeader[pos + 4:pos + 8])[0] itemOffset = unpack('L', fullHeader[pos + 8:pos + 0x0C])[0] itemFilename = fullHeader[pos + 0x18:pos + itemIndexLength].tostring().strip('\0') itemKeyMask = unpack('L', fullHeader[pos + 0x14:pos + 0x18])[0] itemKeyMask = itemKeyMask ^ 0xC7F5DA63 with open(cpzFilename, 'rb') as cpz: cpz.seek(itemOffset + indexLength + 0x14, 0) item = array('B') item.fromfile(cpz, itemLength) getter = ScriptGetter(itemFilename + '.txt', relation_filename, source_path, translated_path, source_encoding, translated_encoding) #只封包relation中定义的文本 if hasattr(getter, 'start_id'): skipcount = getter.start_id decrypt(item, 0, itemLength, 12, itemKeyMask) #解密&解压ps2 decryptPs2(item, 0x30, itemLength - 0x30, unpack('L', item[0x0c:0x10])[0]) itemHeader = item[0:0x30] itemContent = decode(item, 0x30, itemLength - 0x30) scriptLength = unpack('L', itemHeader[0x1C:0x20])[0] scriptOffset = len(itemContent) - scriptLength #读取txt文件,封入封包 txtOffset = 0 #新文本的偏移和长度 textOffset = {} text = '' count = 1 #<则不动的文本的序号297 # skipcount = 297 #不跳过的第一条文本的原偏移。从这个位置开始放入新文本 skipoffset = 0 with open(source_path + itemFilename + '.txt', 'rb') as inputTxtFile: for t in inputTxtFile: if t.startswith(';'): continue if len(t.strip()) == 0: continue if count < skipcount and t.find('=') >= 0: count += 1 continue eq = t.find('=') line = t[eq + 1:].strip('\r\n') + '\0' newline = getter.get_script(codecs.decode(t.split('=')[0], source_encoding)) if newline: try: # temp = codecs.decode(t[eq + 1:].strip('\r\n'), 'shift-jis') line = codecs.encode(newline, translated_encoding) + '\0' pass except UnicodeEncodeError: print "ERROR: can't encode " + newline textOffset[count] = (len(text), len(line)) text += line count += 1 count = 1 lastOffset = (0, 0) j = 0 itemContentString = itemContent.tostring() scriptEnd = scriptOffset - 8 while j < scriptEnd: findJ = itemContentString.find('\x01\x02\x20\x01', j + 1) if findJ >= 0: j = findJ else: break # for j in xrange(0, scriptOffset - 8): # if itemContent[j]+(itemContent[j + 1]<<8)+(itemContent[j + 2]<<16)+(itemContent[j + 3]<<24) == 0x01200201: #unpack 太慢 # if (itemContent[j] == 0x01) and (itemContent[j + 1] == 0x02) and (itemContent[j + 2] == 0x20) and (itemContent[j + 3] == 0x01): #上一行太慢 sentenceOffset = unpack('L', itemContent[j + 4:j + 8])[0] # sentence = itemContentString[scriptOffset + sentenceOffset:scriptOffset + sentenceOffset + 255].split('\0')[0] #slow sentenceEnd = itemContentString.find('\0', scriptOffset + sentenceOffset) sentence = itemContentString[scriptOffset + sentenceOffset:sentenceEnd] if sentence == '': if lastOffset[0] + lastOffset[1] - 1 + skipoffset>0: itemContent[j + 4:j + 8] = array('B', pack('L', lastOffset[0] + lastOffset[1] - 1 + skipoffset)) #itemContent[j + 4:j + 8] = array('B', pack('L', 0)) continue if count < skipcount: count += 1 continue if count == skipcount: skipoffset = sentenceOffset itemContent[j + 4:j + 8] = array('B', pack('L', textOffset[count][0] + skipoffset)) lastOffset = textOffset[count] count += 1 textArray = array('B', text) itemHeader[0x1C:0x20] = array('B', pack('L', len(textArray))) #itemHeader[0x28:0x2C] = array('B', pack('L', scriptOffset + skipoffset + len(textArray))) itemHeader[0x28:0x2C] = array('B', pack('L', scriptOffset * 2 + skipoffset + len(textArray))) #itemContent = itemContent[0:scriptOffset] + textArray itemContent = itemContent[0:scriptOffset + skipoffset] + textArray #压缩 itemContent = encode(itemContent, 0, len(itemContent)) item = itemHeader + itemContent encryptPs2(item, 0x30, len(itemContent), unpack('L', item[0x0c:0x10])[0]) #加密 encrypt(item, 0, len(itemContent) + 0x30, 12, itemKeyMask) itemOffset = len(newCpzContent) newCpzHeader[pos + 8:pos + 0x0C] = array('B', pack('L', itemOffset)) itemLength = len(item) newCpzHeader[pos + 4:pos + 8] = array('B', pack('L', itemLength)) #将此内容加入 newCpzContent.fromstring(item.tostring()) print itemFilename + ' added' pos += itemIndexLength i += 1 delta = 12 - 20 encrypt(newCpzHeader, 0x14, indexLength + 0x14, delta, keyMask) indexCount = unpack('L', newCpzHeader[4:8])[0] ^ 0x5E9C4F37 newCpzHeader[4:8] = array('B' , pack('L', indexCount)) indexLength = unpack('L', newCpzHeader[0x8:0xC])[0] ^ 0xF32AED17 newCpzHeader[0x8:0xC] = array('B' , pack('L', indexLength)) keyMask = unpack('L', newCpzHeader[0x10:0x14])[0] ^ 0xDDDDDDDD newCpzHeader[0x10:0x14] = array('B' , pack('L', keyMask)) with open(newFilename, 'wb') as newCpz: newCpzHeader.tofile(newCpz) # for i in (0x33 ,0x25 ,0xAD ,0xBA ,0xA5 ,0x22 ,0x31 ,0xF1 ,0x08 ,0x69 ,0x82 ,0xC2 ,0xFE ,0xCC ,0x16 ,0x47): # newCpz.write(chr(i)) newCpzContent.tofile(newCpz)