def upload_files(): TIME_DIR = os.path.join(time.strftime('%Y%m%d'), time.strftime('%H')) if request.method == 'POST': f = request.files['file'] fname = secure_filename(f.filename) if len(fname.split('_')) >= 3: event_dir = os.path.join(SAVE_DIR, fname.split('_')[0], TIME_DIR) time_lzo_dir = os.path.join(unlzo_dir, fname.split('_')[0], TIME_DIR) if os.path.isfile(time_lzo_dir): os.remove(time_lzo_dir) if not os.path.exists(time_lzo_dir): os.makedirs(time_lzo_dir) if os.path.isfile(event_dir): os.remove(event_dir) log_file = open('file_dirtofile.log', 'a') log_file.write(time.ctime() + '\n') log_file.close() if not os.path.exists(event_dir): try: os.makedirs(event_dir) except OSError: pass lzo_md5 = request.headers.get('LZO-MD5') save_path = os.path.join(TEMP_DIR, fname) f.save(save_path) if lzo_md5 and lzo_md5 == cal_md5(os.path.join(TEMP_DIR, fname)): if event_dir: shutil.move(os.path.join(TEMP_DIR, fname), event_dir) source_ball_name = os.path.join(event_dir, fname) rc4.decrypt(os.path.join(event_dir, fname)) save_unlzo_dir = os.path.join(time_lzo_dir, fname + '.csv') unlzo = os.popen('/usr/bin/lzom -d %s %s' % (source_ball_name, save_unlzo_dir)) return json.dumps({ 'rc': 0, 'stats': 'finished', 'msg': 'file upload sucess.', 'filename': f.filename, }) else: return json.dumps({ 'rc': -2, 'stats': 'close', 'msg': 'file name error.', 'filename': f.filename, }) else: return json.dumps({ 'rc': -1, 'stats': 'close', 'msg': 'md5 didn\'t match.', 'filename': f.filename, }) return '''<!doctype html>
def TestDecryptSmall(): """ Test decrypt with small key """ expected = "Plaintext" decrypt("Key", "decryptSmallC.txt", "decryptSmallP.txt") with open("decryptSmallP.txt", "rb") as myfile: result = myfile.read() print "Expected: " + expected print "Result: " + result assert result == expected
def TestDecryptLong(): """ Test decrypt with a longer key """ expected = "pedia" decrypt("Wiki", "decryptLongC.txt", "decryptLongP.txt") with open("decryptLongP.txt", "rb") as myfile: result = myfile.read() print "Expected: " + expected print "Result: " + result assert result == expected
def TestDecryptMultipleWords(): """ Test decrypt with long key and multiple words """ expected = "Attack at dawn" decrypt("Secret", "decryptMultipleC.txt", "decryptMultipleP.txt") with open("decryptMultipleP.txt", "rb") as myfile: result = myfile.read() print "Expected: " + expected print "Result: " + result assert result == expected
def upload_files(): TIME_DIR = os.path.join(time.strftime('%Y%m%d'), time.strftime('%H')) if request.method == 'POST': f = request.files['file'] fname = secure_filename(f.filename) if len(fname.split('_')) >= 3: event_dir = os.path.join(SAVE_DIR, fname.split('_')[0], TIME_DIR) time_lzo_dir = os.path.join(unlzo_dir,fname.split('_')[0],TIME_DIR) if os.path.isfile(time_lzo_dir): os.remove(time_lzo_dir) if not os.path.exists(time_lzo_dir): os.makedirs(time_lzo_dir) if os.path.isfile(event_dir): os.remove(event_dir) log_file = open('file_dirtofile.log', 'a') log_file.write(time.ctime() + '\n') log_file.close() if not os.path.exists(event_dir): try: os.makedirs(event_dir) except OSError: pass lzo_md5 = request.headers.get('LZO-MD5') save_path = os.path.join(TEMP_DIR, fname) f.save(save_path) if lzo_md5 and lzo_md5 == cal_md5(os.path.join(TEMP_DIR, fname)): if event_dir: shutil.move(os.path.join(TEMP_DIR, fname), event_dir) source_ball_name = os.path.join(event_dir,fname) rc4.decrypt(os.path.join(event_dir, fname)) save_unlzo_dir = os.path.join(time_lzo_dir,fname+'.csv') unlzo = os.popen('/usr/bin/lzom -d %s %s' % (source_ball_name,save_unlzo_dir)) return json.dumps({ 'rc': 0, 'stats': 'finished', 'msg': 'file upload sucess.', 'filename': f.filename, }) else: return json.dumps({ 'rc': -2, 'stats': 'close', 'msg': 'file name error.', 'filename': f.filename, }) else: return json.dumps({ 'rc': -1, 'stats': 'close', 'msg': 'md5 didn\'t match.', 'filename': f.filename, }) return '''<!doctype html>
def dataReceived(self, data): # NOTE: this might be slow, convert to hex before sending? data = rc4.decrypt(KEY, data.hex()) test = json.loads(data) print("RECV: {}".format(test)) if test['command'] == 'move': # do things here d = test['arguments']['direction'] if d == 'up': self.y -= SPEED elif d == 'down': self.y += SPEED elif d == 'left': self.x -= SPEED elif d == 'right': self.x += SPEED ret_data = json.dumps(foo(self.x, self.y)).encode() # ... # enc_data = rc4.encrypt(KEY, str(ret_data)) # str? # enc_data = bytes(enc_data.encode('utf-8')) # print(ret_data, enc_data); quit() # self.transport.write(enc_data) # print('*** sent ***'); quit() self.transport.write(ret_data)
def decrypt_data(key, data, algorithm="rc4", use_custom_rc4=False): """ Decrypts data with key and specified algorithm. """ if algorithm == "rc4": return rc4.decrypt(key, data, use_custom_rc4) elif algorithm == "rc5": cryptor = RC5(key) cryptor.mode = "CBC" return cryptor.decrypt(bytes(data))
async def _consumer_handler(ws, key): global inc2 ciphertext = await ws.recv() if ENCRYPTION: plaintext = rc4.decrypt(key, ciphertext) else: print(ciphertext) inc2 += 1 await asyncio.sleep(.1)
def run(self): while 1: data = self.clientsocket.recv(variables.buf) #Recieve data if not data: #If empty, break break #Decrypt data using RC4 data = rc4.decrypt(data, variables.rounds, variables.key) #Determine time that message was received (UTC timezone) now = datetime.datetime.now() now = now.strftime("%A, %B %d, %y at %r UTC") data = now + '\n' + data variables.messages.append(data) return
def dataReceived(self, data): plain = decrypt(data,key) print plain msg = pynmea2.parse(plain) sql = "INSERT INTO gpsdata (imei,latitude,longitude,date_time)" sql += " VALUES ('%s', %f, %f, '%s')" % (imei,msg.latitude,msg.longitude,msg.timestamp) print "data terencrypt : %s" % data print "data plain : %s " % plain print "QUERY SQL :%s" % sql #print msg.datestamp #print msg.longitude self.transport.write("OK")
def decrypt_RC4(): start_time = time() global decrypttext_rc4_in_str print("Cipher Message : ", cipher_rc4_message) plain_aes = cipher_rc4_message key = rc4_key.get() print("Key : ", key) decrypttext_rc4 = decrypt(plain_aes, key) decrypttext_rc4_in_str = bytes.decode(decrypttext_rc4) print("Normal Message : ", decrypttext_rc4_in_str) output_rc4.insert(tk.END, "%s" % (decrypttext_rc4_in_str)) end_time = time() time_taken = end_time - start_time hours, rest = divmod(time_taken, 3600) minutes, seconds = divmod(rest, 60) print("Time taken : ", format_timespan(end_time - start_time)) messagebox.showinfo("Success!", "Decrypt RC4 Success")
def process_message(msg): global message_stack try: msg = json.loads(msg) except: return None if msg.get('username') != config.username or msg.get('node') == platform.node(): return None if msg.get('first'): message_stack = [] message_stack.append(msg) if msg.get('last'): message_stack.sort(key=lambda x: x.get('order')) message = '' for m in message_stack: message += m['msg'] message = rc4.decrypt(message, config.password) message_stack = [] return message return None
def process_message(msg): global message_stack try: msg = json.loads(msg) except: return None if msg.get('username') != config.username or msg.get( 'node') == platform.node(): return None if msg.get('first'): message_stack = [] message_stack.append(msg) if msg.get('last'): message_stack.sort(key=lambda x: x.get('order')) message = '' for m in message_stack: message += m['msg'] message = rc4.decrypt(message, config.password) message_stack = [] return message return None
import rc4 key = "thisisatestkey" ciphertext = "D8AB52DE7805545A0FD1D16300FB3B7B0BAC" print(rc4.decrypt(key, ciphertext))
def get(self): data = self.request.get('data').encode('utf-8') data = simplejson.loads(data) weak = data['weak'] key = weak.encode('ascii', 'replace') weak_hash = hashlib.sha224(key).hexdigest() charset = PASSWORD_SET options = dict() options['uppercase'] = options['lowercase'] = options['numeric'] = True options['special'] = False if data['chars']: options = data['chars'] if options['uppercase'] or options['lowercase'] or options['numeric'] or options['special']: charset = '' if options['uppercase']: charset += string.ascii_uppercase if options['lowercase']: charset += string.ascii_lowercase if options['numeric']: charset += string.digits if options['special']: charset += "!#$%&'()*+,-./:;=?@[\]^_`{|}~" else: options['uppercase'] = options['lowercase'] = options['numeric'] = True options['special'] = False password = Password.all() password = password.filter('weak =', weak_hash) password = password.filter('lowercase =',options['lowercase']) password = password.filter('uppercase =',options['uppercase']) password = password.filter('digits =',options['numeric']) password = password.filter('special =',options['special']) password = password.get() if not password: randoms = get_random_passwords(n=PASSWORD_NUMBER, len=PASSWORD_LENGTH, set=charset) password = Password( weak = weak_hash, uppercase = options['uppercase'], lowercase = options['lowercase'], digits = options['numeric'], special = options['special'] ) for r in randoms: r = rc4.encrypt(r,key) password.strong.append(r) password.encrypted = True password.put() if password.encrypted == True: for i in range(len(password.strong)): password.strong[i] = rc4.decrypt(password.strong[i], key) else: encrypt_and_put(password, key) # Integrate old passwords if len(password.strong) is 0: merge_old_passwords(password, charset) encrypt_and_put(password, key) # if the PASSWORD_NUMBER has been altered if len(password.strong) < PASSWORD_NUMBER: fill_up_password_number(password, charset) encrypt_and_put(password, key) if len(password.strong) > PASSWORD_NUMBER: password.strong = password.strong[:PASSWORD_NUMBER] # if the PASSWORD_LENGTH has been altered if len(password.strong[0]) < PASSWORD_LENGTH: fill_up_password_length(password, charset) encrypt_and_put(password, key) if len(password.strong[0]) > PASSWORD_LENGTH: for i in range(len(password.strong)): password.strong[i] = password.strong[i][:PASSWORD_LENGTH] # Encode using the GQL Encoder rest = list() for i in range(len(password.strong)): rest.append({'id': i, 'password': password.strong[i][:data['length']]}) data = simplejson.dumps(rest) self.response.headers['Content-Type'] = 'application/json; charset=utf-8' self.response.out.write(data)
def crack(enc_packets): ''' Crack the password ''' count = 0 A_matrix = np.zeros((13, len(enc_packets)), dtype=np.uint8) print(" Analyzing Packets. %s." % time.ctime()) if os.path.isfile('./veryimportantmatrix.npy'): A_matrix = np.load('./veryimportantmatrix.npy') else: for packet in enc_packets: src = 'B' if count % 2 == 0: src = 'A' keystream = [] for number in range(3, 36, 2): # Keystream calc pbyte = int(packet[number:number + 2], 16) # Convert from Hex keystream.append(ord(src) ^ pbyte) # Build keystream packet_analysis(packet, A_matrix[:, count], keystream) count += 1 np.save('veryimportantmatrix', A_matrix) ''' print(" Determing Results %s." % time.ctime()) number_of_answers = 2 frequent_answers = np.zeros((13, number_of_answers), dtype=np.uint8) for i in range(13): # Building a two dimensional array of most frequent_answers y = np.bincount(A_matrix[i, :]) for k in range(number_of_answers): index = np.argmax(y) frequent_answers[i][k] = y[index] y[index] = 0 print frequent_answers def get_Rk(sigma): Rk = np.zeros(13, dtype=np.uint8) Rk[0] = sigma[0] for i in range(1, 13): Rk[i] = sigma[i] - sigma[i - 1] return Rk for j in range(number_of_answers): sigma = np.zeros(13, dtype=np.uint8) sigma[0] = frequent_answers[0][j] for i in range(1, 13): sigma[i][j] = frequent_answers[i][j] print get_Rk(sigma) ''' print(" Determing Results %s." % time.ctime()) sigma = [] for x in range(13): sigma.append(np.argmax(np.bincount(A_matrix[x,:]))) Rk = np.zeros((13), dtype=np.uint8) Rk[0] = sigma[0] for i in range(1, 13): Rk[i] = ((sigma[i] - sigma[i - 1])) print(" Key is %s. %s." % (str(Rk), time.ctime())) print(" Key is %s. %s." % (str([chr(item) for item in Rk]), time.ctime())) for item in enc_packets: packet = item[3:] key = packet[0:3] + ''.join(str(s) for s in Rk) key_array = rc4.key_schedule(key) keystream = rc4.get_keyStream(key_array, len(packet)) print rc4.decrypt(packet, keystream)
def test_decrypt(): rc4.decrypt("Key", "cipherfile.txt", "result.txt") assert(filecmp.cmp('plainfile.txt', 'result.txt'))
def test_wave_decrypt(): rc4.decrypt("Moon", "neilc.wav", "result.wav") assert(filecmp.cmp('neil.wav', 'result.wav'))