def computeJiSquared(aEncode): # diccionario con frec de muestra español. sampleTextDictionary = frecuencias.frecuencias() for i in range(1, 26): #For cycle from the first letter to last encodedTextSwap = encoder.encode(aEncode, i) #recorremos el texto 26 veces ji = 0 encodedTextDictionary = frecuencias.frecuenciaTexto( encodedTextSwap) # sacamos la frecuencia de cada movimiento for n in range(len(ABECEDARIO)): charToProcess = ABECEDARIO[ n] #de la lista de abecedario sacamos cada letra. #sacamos la freuencia de cada letra de ambos diccionarios: charEncodedText = encodedTextDictionary.get(charToProcess) charSampleText = sampleTextDictionary.get(charToProcess) # error de div entre 0. if charSampleText == 0: charSampleText = 0.0000000000000001 #Se calcula la ji cuadrada de cada letra de cada iter. ji = ji + ((charEncodedText - charSampleText) * (charEncodedText - charSampleText)) / charSampleText dicJI[ i] = ji # se agrega a diccionario de ji cuadrada donde i es el swap. swap = 26 - min( dicJI, key=dicJI.get ) # Se busca el menor ji cuadrado y se resta el total de iter para sacar la diferencia. print(createTables.createJiTable(dicJI)) # tablas print('\n\nThe right one should be: ', encoder.encode(aEncode, -swap), '\n swap: ', swap, '\n\n') return swap
def process(): if request.method == "GET": query = request.args.to_dict() print("Received GET Query:", query) return Response(encode(query), mimetype='proton') else: decoded = decode(request.data) print("Received POST ProtoN Message:", decoded) return Response(encode(decoded), mimetype='proton')
def main(argv): plaintext = "The quick brown fox jumps over the lazy dog" ciphertext = "1442779157967667200000|262059538099831245374033664000000000|491524481646305217710445277411617404468653198242187500|54736736297607421875000000|26575780025450776966354193208522490921501091250000000000|5232777644455317290286534758400000|21499084800000|24555699822948576064581298828125000000000000|17936133750000" # this would be less ugly if python had the ternary operator hexadecimal = True if "--hex" in argv else False if "--encode" in argv: print encoder.encode(plaintext, hexadecimal) if "--decode" in argv: print decoder.decode(ciphertext)
def test_large_file(self): stream = bytearray('') try: os.remove('warandpeace2.txt') except OSError: pass encode('warandpeace.txt', stream) decode(stream, 'warandpeace2.txt') self.assertEqual(filecmp.cmp('warandpeace.txt','warandpeace2.txt'), True)
def main(): if len(sys.argv) != 3: print('use: sudoku_solver <sudoku_instances_file> <encoding>') exit(1) if sys.argv[2] != '1' and sys.argv[2] != '2': print('use 1 for minimal or 2 for extendend in encoding') exit(1) if not os.path.isfile('./build/release/bin/minisat'): print('run `make r` first') exit(1) # Get constant clauses encoding = int(sys.argv[2]) clauses_string = clauses(encoding) sudoku = NINExNINE instances = open(sys.argv[1],'r') solution_file = open('solution','w') minisat_solname = 'sudoku_solution' sudoku_cnf = 'sudoku.cnf' for inst in instances: for i in range(0, 81): sudoku[i//9][i%9] = inst[i] encode(sudoku, clauses_string, encoding) # Get a solution and measure it's time start = time.time() subprocess.call(['./build/release/bin/minisat', sudoku_cnf, minisat_solname], stdout = open(os.devnull, 'w'), stderr = open(os.devnull, 'w')) delta = time.time() - start # If the file was created if os.path.isfile(minisat_solname): solution_file.write("-----------------------\ninstance: '" + inst + "'\ntime: " + str(delta) + '\n\n') decode(minisat_solname, solution_file) else: print("there is no solution for the instance '" + inst[:-1] +"'\n") if os.path.isfile(minisat_solname): os.remove(minisat_solname) os.remove(sudoku_cnf) instances.close() solution_file.close() # If this is the module running if __name__ == '__main__': main()
def __init__(self, chunks, encoder=None, char='\n', skip_delimeter=True): char = encoder.encode(char) chunks = chunks[0] l = [] self.chunks = [] for i in chunks: if i != char[0] or not skip_delimeter: l.append(i) else: l.append(encoder.encode(' ')[0]) #l.append(encoder.encode('.')[0]) if i == char[0]: self.chunks.append(l) l = [] self.total_size = len(self.chunks)
def network(cont_plce_hlder, que_plce_hlder, context_mask_placeholder, question_mask_placeholder, ans_plce_hlder, dropout_placeholder): G = encode(cont_plce_hlder, context_mask_placeholder, que_plce_hlder, question_mask_placeholder, drop_out, hidden_states, max_para_lgth) pred_ans = decode(G, context_mask_placeholder, drop_out, hidden_states) print(pred_ans) loss = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=ans_plce_hlder, logits=pred_ans)) params = tf.compat.v1.trainable_variables() gradients = tf.gradients(loss, params) gradient_norm = tf.linalg.global_norm(gradients) clipped_gradients, _ = tf.clip_by_global_norm(gradients, max_gradient_norm) param_norm = tf.linalg.global_norm(params) global_step = tf.Variable(0, name="global_step", trainable=False) opt = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate) updates = opt.apply_gradients(zip(clipped_gradients, params), global_step=global_step) return updates, loss, global_step, param_norm, gradient_norm, pred_ans
def ext_upload_chunked_part(chunk): _api = GoogleAPI() # print("Chunk %s, bytes %s to %s" % (chunk.part, chunk.range_start, chunk.range_end)) with open(chunk.path, "r") as fd: mm = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) chunk_bytes = mm[chunk.range_start:chunk.range_end] encoded_chunk = encoder.encode(chunk_bytes) file_metadata = { 'name': chunk.media.name + str(chunk.part), 'mimeType': 'application/vnd.google-apps.document', 'parents': [chunk.parent], 'properties': { 'part': str(chunk.part) } } mediaio_file = MediaIoBaseUpload(io.StringIO(encoded_chunk), mimetype='text/plain') _api.upload_single_file(mediaio_file, file_metadata) return len(chunk_bytes)
def main() -> None: file = argv[1] pixels = TGAParser(file).get_pixels() predictors_entropies = {} print("Entropies for tga image.") pprint(get_entropies(pixels)) print(31 * "-") print("Entropies for encoded image, per predictor.") for predictor in predictors: encoded = encode(pixels, predictor) entropies = get_entropies(encoded) predictors_entropies[predictor.__name__] = entropies print("\033[32m" + predictor.__name__ + "\033[0m") pprint(entropies) print(31 * "-") def best_predictor(stat: str) -> Tuple[str, Dict[str, float]]: return min(predictors_entropies.items(), key=lambda predictor: predictor[1][stat]) print("--------Best predictors--------") print(f"general: {best_predictor('general')}") print(f"red: {best_predictor('red')}") print(f"green: {best_predictor('green')}") print(f"blue: {best_predictor('blue')}")
def upload_chunked_part(self, chunk, api=None): """Upload a chunked part to drive and return the size of the chunk""" if not api: api = self.api with open(chunk.path, "r") as fd: mm = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) chunk_bytes = mm[chunk.range_start:chunk.range_end] encoded_chunk = encoder.encode(chunk_bytes) file_metadata = { 'name': chunk.media.name + str(chunk.part), 'mimeType': 'application/vnd.google-apps.document', 'parents': [chunk.parent], 'properties': { 'part': str(chunk.part) } } mediaio_file = MediaIoBaseUpload(io.StringIO(encoded_chunk), mimetype='text/plain') self.api.upload_single_file(mediaio_file, file_metadata) return len(chunk_bytes)
def __init__(self, argv): self.rules = parser.parse(argv[1]) self.tape = encoder.encode(argv[2]) self.init_tape = self.tape self.padding = Symbol.by_rep("_") self.index = 0 self.state = State(0)
def test_encode(): text = "Litwo, Ojczyzno moja! ty jesteś jak zdrowie;\nIle cię trzeba cenić, ten tylko się dowie" sorted_words = "Litwo Ojczyzno cenić dowie jesteś moja trzeba tylko zdrowie" encoded_text = encoder.encode(text) parts = encoded_text.split(encoder.SEPARATOR) assert len(parts) == 3 # check if text contains 2 separators assert parts[2] == sorted_words
def encode(args): with open(args.infile.name, args.infile.mode) as file: code = cleanup(file.read()) with open(args.outfile.name, args.outfile.mode) as file: data = encoder.encode(code) file.write(data)
def newWallet(): # Creates a new wallet and key for use with Hehecoin Core keyGen() info = {"Address": addressGen(), "Coins": 0} j = json.dumps(info) j = encoder.encode(getKey(), j) with open("wallet.txt", "w+") as f: f.write(j)
def test_decode_ambiguous(): text = "mango magno" encoded = encoder.encode(text) decoded = encoder.decode(encoded) decoded = decoded.split() assert decoded[0] == "magno" or decoded[0] == "mango" assert decoded[1] == "magno" or decoded[1] == "mango"
def test(ctx, enc, dec, gdc, test_data): global test_idx ae_metric = mx.metric.MSE() gd_metric = mx.metric.Accuracy() samples = [] for images, labels in test_data: gauss_yes = nd.ones((labels.shape[0], 1), ctx=ctx) features = encode(enc, images, labels) images_out = decode(dec, features, labels) ae_metric.update([images], [images_out]) gauss_fit = gdc(features) gd_metric.update([gauss_yes], [gauss_fit]) idx = np.random.randint(images.shape[0]) samples.append( mx.nd.concat(images[idx], images_out[idx], dim=2)[0].asnumpy()) name, mse = ae_metric.get() print(' AutoEncoder: {}={:.4f}'.format(name, mse)) name, mse = gd_metric.get() print(' GaussDiscriminator: feature space satisfaction {}={:.4f}'.format( name, mse)) try: imgdir = '/tmp/mnist' save_images(samples[::2], imgdir, test_idx * 1000) test_idx += 1 print(" test images written to", imgdir) except Exception as e: print(" writing images failed:", e)
def main(): total_score = 0 total_cases = 4 for i in range(0, total_cases): file_name = "../datasets/input/" + str(i) + ".txt" message = open_file(file_name) if not is_binary_message(message): message = str_to_bits(message) # # Main Algorithm # coded_transmission = encode(message) received_message = corrupt_message(coded_transmission) channel_file_name = "../datasets/channel/" + str(i) + ".txt" save(channel_file_name, received_message) decoded_message = decode_message(received_message) output_file_name = "../datasets/output/" + str(i) + ".txt" save(output_file_name, decoded_message) # Evaluate the Approach score = evaluate_bits(message, decoded_message) print("Message: " + str(i) + " => Accuracy: " + str(score) + "%") total_score += score print("Average Accuracy: " + str(average(total_score, total_cases)) + "%")
def encrypt(): if request.method == 'POST': # check if the post request has the file part if 'up_pic' not in request.files: return "No file selected" return redirect(request.url) file = request.files['up_pic'] degree = int(request.form.get('degree')) pwd = request.form.get('pwd') # if user does not select file, browser also # submit a empty part without filename if file.filename == '': return "No file selected" return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) links = [str(os.path.join(app.config['UPLOAD_FOLDER'], filename))] if request.form['submit']=="enc": (im,arr,path)=enc.encode(links[0],degree,pwd) else: (im,arr,path)=dec.decode(links[0],degree,pwd) links.append(path) return render_template("display.html",link=links)
def send(self, dst, t, msg): assert type(dst) == type(""), type(dst) assert dst != "" msg["src"] = self.me msg["type"] = t msg["dst"] = dst msg["networkid"] = networkid events.append(lambda: nodes[dst].incoming(self.me, encoder.encode(msg)))
def main(): """ Simple example entry point""" message = 'Better Faster Forever' cipher = make_cipher('QWERTY') secret = encode(message, cipher) print('secret: {}'.format(secret)) # secret: vTnnTl zQmnTl zilTpTl print(decode(secret, cipher))
def exitProgram( d=None ): # Provides the user with a prompt before exiting. If given a dictionary, encodes it accordingly and saves to wallet.txt if not d == None: with open("wallet.txt", "w") as f: f.write(encoder.encode(getKey(), json.dumps(d))) input("\nPress enter to exit...\n") quit()
def post(self): try: response = make_response( encode(request.get_data().decode("utf-8")), 200) except UnicodeDecodeError: response = make_response("Error: body is not valid unicode", 400) response.mimetype = "text/plain" return response
def test_encode(self): raised = False try: self.assertTrue(encoder.encode()) except: raised = True print traceback.print_exc(file=sys.stdout) self.assertFalse(raised, "Exception raised")
def reset(): context = request.context email = request.form.get('email', '') if email == '': return render_template('reset_request.html') context['email'] = encoder.encode(email) return render_template('sent_reset.html', **context)
def decode_BruteForce(text): results = [] for i in range(1, 28): #For cycle from the first letter to last decoded = encoder.encode(text, -i) result = 'Attempt ' + str(i) + ' Message: ' + str(decoded) print(result) results.append(decoded) answer = getAnswer(results) print('\n\nThe right one should be: ', answer)
def on_encode_clicked(self, button): buffer = self.message_to_encode.get_buffer() (start, stop) = buffer.get_bounds() message_to_encode = buffer.get_text(start, stop, 0) encoded_message = encode(message_to_encode, self.shift_input.get_value_as_int()) # display the encoded message self.encoded_label.set_text(encoded_message)
def get_matches(face_reid_model, face, ret_encoded_face=False): encoded_face = encode(face_reid_model, face) script_query = get_script_query(encoded_face) search_response = es_search(es_client, script_query) result = Counter([ hit['_source']['id'] for hit in search_response['hits']['hits'] if hit['_score'] > 0.60 ]) if ret_encoded_face: return encoded_face, result else: return result
def search_page(): context = request.context search = request.args.get('s', '') if search != '': wildcard = '%' + search + '%' query = """SELECT USER_PATH_ID FROM users WHERE username LIKE (?);""" users = query_db(query, (wildcard,)) context['users'] = encoder.encode_qry(users) context['query'] = encoder.encode(search) return render_template('search_results.html', **context) return redirect('/')
def decoder(toDecode): # diccionarios de frecuencias dicFrecTDecode = frecuencias.frecuenciaTexto(toDecode) dicSample = frecuencias.frecuencias() # sacamos el maximo valor de cada diccionario ascii indexToDecod = ord(max(dicFrecTDecode, key=dicFrecTDecode.get)) indexSample = ord(max(dicSample, key=dicSample.get)) # La diferencia de los dos maximos valores es el swap. deltaIndex = indexToDecod - indexSample #LLamamos a enocoder para mover el texto con el swap degativo. decoded = encoder.encode(toDecode, -deltaIndex) return ("Message Received: %s\nSwap Key: %i\nDecoded Message: %s" % (toDecode, deltaIndex, decoded))
def test_encoding_with_error_correction(): # binary encoding test with error correction expected_bin = [ '000', '000', '000', '010', '010', '000', '001', '010', '001', '011', '000', '000', '000', '011', '011', '000', '000', '000', '011', '011', '000', '001', '000', '001', '110', '000', '000', '010', '010', '100', '000', '001', '000', '010', '011', '000', '001', '000', '001', '110', '000', '000', '000', '100', '010', '000', '000', '000', '011', '011', '000', '000', '001', '000', '010' ] assert expected_bin == encode( 'Hello World', 3), "Binary encoding is incorrect to expected output." print("Binary encoding:", encode('Hello World', 3)) # binary to integer encoding test with error correction expected_int = [ 0, 0, 0, 2, 2, 0, 1, 2, 1, 3, 0, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 1, 0, 1, 6, 0, 0, 2, 2, 4, 0, 1, 0, 2, 3, 0, 1, 0, 1, 6, 0, 0, 0, 4, 2, 0, 0, 0, 3, 3, 0, 0, 1, 0, 2 ] assert expected_int == to_ints(encode( 'Hello World', 3)), "Binary to integer encoding is incorrect to expected output." print("Binary to integer encoding:", to_ints(encode('Hello World', 3)))
def callback(self): if self.channel.startswith('#'): if 'b64' in self.message: self.user = encoder.encode('b64:' + self.user) if self.command.lower() == 'hello': return self.msg( self.channel, "And a hello to you too, " + ("operator" if self.isop else "user") + " %s (%s)!" % (self.profile.username, self.profile.userhost)) return self.msg( self.channel, "and a henlo 2 u STINKY, " + ("operator" if self.isop else "user") + " %s (%s), go post a shit ugly" % (self.profile.username, self.profile.userhost))
def sendCoin(send, n): # "Sends" coins to an address showWallet() d = getWallet() if n <= 0: print("You cannot do that.") input("Press enter to continue...") elif n > d["Coins"]: print("You do not have " + str(n) + " coins to send. Please try again") input("Press enter to continue...") else: d["Coins"] -= n with open("wallet.txt", "w") as f: f.write(encoder.encode(getKey(), json.dumps(d))) showWallet() print(str(n) + " coins have been transferred to that address.") input("Press enter to continue...")
def api(request): response = {} if request.method == 'GET': # Return encoded message (soundprint) if request.GET.get('message'): response['soundprint'] = encoder.encode(request.GET['message']) # Return decoded message elif request.GET.get('soundprint'): response['message'] = decoder.decode(request.GET['soundprint']) else: response['error'] = 'missing 1 parameter (message or soundprint)' else: response['error'] = 'must send GET request' return HttpResponse(json.dumps(response, indent=4), \ content_type='application/json')
def execute(request): if request.method == 'POST': form = Signal_info(request.POST) if form.is_valid(): str = request.POST['signals'] size_original = len(str) params = [int(s) for s in str.split()] step = int(request.POST['step']) params_by_step = params[::step] size_by_step = size_list_to_str(params_by_step) params_by_step_dict = to_dec(params_by_step) temp = encode(params_by_step, params_by_step_dict) encoded_params_by_step = temp[0] savetofile(encoded_params_by_step, 'encoded') binary_dict = temp[1] savedict(binary_dict, 'code_dict') size_encoded = len(encoded_params_by_step) return render_to_response('graphic_answer.html', {'params': params, 'entropy': round(entropy_unprepared(params), 2), 'params_by_step': params_by_step, 'entropy_step': round(entropy(params_by_step_dict, len(params_by_step)), 2), 'step': step, 'encoded_params_by_step':encoded_params_by_step, 'size_original':size_original, 'size_by_step':size_by_step, 'size_encoded':size_encoded, 'dict':binary_dict, 'or_en':size_original - size_encoded, 'or_step':size_original - size_by_step, 'step_en':size_by_step-size_encoded, 'decoded_signals':decoder.decode(encoded_params_by_step, binary_dict), }, context_instance=RequestContext(request)) else: form = Signal_info() return render(request, 'preview.html', {'form': form})
def test_multiple_files(self): stream = bytearray('') try: os.remove('a2.txt') os.remove('b2.txt') os.remove('c2.txt') except OSError: pass encode('a.txt', stream) encode('b.txt', stream) encode('c.txt', stream) decode(stream, 'a2.txt') decode(stream, 'b2.txt') decode(stream, 'c2.txt') self.assertEqual(filecmp.cmp('a.txt','a2.txt'), True) self.assertEqual(filecmp.cmp('b.txt','b2.txt'), True) self.assertEqual(filecmp.cmp('c.txt','c2.txt'), True)
def get_short_id(self, id): res = self.__id_dict.get(id) if res is None: res = encode(len(self.__id_dict)) self.__id_dict[id] = res return res
def test_encoding(self): self.assertTrue(encode(self.input) == self.output)
def command_cb(word, word_eol, userdata): msg = None key = None hashsys = "sha1" mutate = False mutatekey = "" say = False sayloud = False if len(word) < 2: xchat.prnt("You must specify whether you want to encode or decode: /a04 encode|decode") return xchat.EAT_ALL act = word[1] if act != "encode" and act != "decode": xchat.prnt("You must specify whether you want to encode or decode: /a04 encode|decode") return xchat.EAT_ALL for cmd in " ".join(word[2:]).split("--"): if cmd.startswith("msg "): msg = cmd[4:].strip() if cmd.startswith("key "): key = cmd[4:].strip() if cmd.startswith("hash "): hashsys = cmd[5:].strip() if cmd.strip() == "mutate": mutate = True if cmd.startswith("mutatekey "): mutatekey = cmd[10:].strip() if cmd.strip() == "say": say = True if cmd.strip() == "loud": sayloud = True if msg is None: xchat.prnt("You must specify a message to " + act + ": /a04 " + act + " --msg <msg>") return xchat.EAT_ALL if key is None: xchat.prnt("You must specify a key to " + act + ": /a04 " + act + " --key <key>") return xchat.EAT_ALL if act == "encode": encoded = encode(msg, key, hashsys, False, mutate) out = " ".join(encoded[0]) if filter(None, encoded[1]) != []: out += " (mutation key: " + ":".join(encoded[1]) + ")" if say: if sayloud: xchat.get_context().command("say " + hashsys + " | " + key + " | " + out) else: xchat.get_context().command("say " + out) else: xchat.prnt("encoded message: " + out) if act == "decode": decoded = decode(msg, key, hashsys, False, False, mutate, mutatekey) if decoded == "": xchat.prnt("the decoder couldn't decode anything for the given message") else: if say: xchat.get_context().command("say decoded message: " + decoded) else: xchat.prnt("decoded message: " + decoded) return xchat.EAT_ALL
exit(1) messageFile = open(sys.argv[1], 'r') message = "" lines = messageFile.readlines() messageFile.close() #Load the lines of the meassage file to a string for l in lines: message += l; #Set the block length for the encoder encoder.BLOCKLENGTH = int(sys.argv[2]) blocks = encoder.encode(message) #Encode to a list of integers #Read the Public Key keyFile = open("K1", 'r') p = int(keyFile.readline()) g = int(keyFile.readline()) h = int(keyFile.readline()) keyFile.close(); key = elgamal.PublicKey(p,g,h) #Encrypt each block and write to file cipherFile = open("Cipher", 'w') for b in blocks: c = elgamal.encrypt(b, key) cipherFile.write("%s\n" % c)
parser.add_option("-f", "--file", type="string", dest="filename", help="FILE to encode or decode", metavar="FILE") parser.add_option("-e", "--encode", action="store_true", dest="encoder", help="Encode plain text file") parser.add_option("-d", "--decode", action="store_false", dest="encoder", help="Decode previously encoded file") parser.add_option("-p", "--password", type="string", dest="password", help="Password to encode / decode") parser.add_option("-t", "--test", action="store_true", dest="debug") (options, args) = parser.parse_args() if options.debug: # verify basic functionality teststring = "The quick brown fox jumped over the lazy dog" testpwd = "password" encoded = encode(teststring,testpwd) assert(teststring != encode(teststring,testpwd)) assert(testpwd != encode(teststring,testpwd)) assert(encode(teststring,"wrongpwd") != encode(teststring,testpwd)) assert(teststring == decode(encoded,testpwd)) # try increasingly difficult strings teststring = "Adding numbers 12345" assert(teststring == decode(encode(teststring,"password"),"password")) teststring = "Adding special chars @#$(*^,;'" assert(teststring == decode(encode(teststring,"password"),"password")) teststring = 'with double quotes"' assert(teststring == decode(encode(teststring,"password"),"password")) print "Success!" exit(0) if not options.password:
print '|', ' | '.join(str(x).rjust(COL_WIDTH) for x in [file, original, gz, encoded, enc_gz]), '|' if __name__ == '__main__': if not os.path.exists('target'): os.mkdir('target') print_table_header() print_separator() for file in os.listdir('data'): try: if file.endswith('.txt'): os.system('gzip -fk9 data/%s' % file) shutil.move('data/%s.gz' % file, 'target/%s.gz' % file) encoder.encode('data/'+file, 'target/'+file+'.encoded') os.system('gzip -fk9 target/%s.encoded' % file) print_table_entry(file, fsize('data/'+file), fsize('target/'+file + '.gz'), fsize('target/'+file + '.encoded'), fsize('target/'+file + '.encoded.gz')) encoder.decode('target/'+file + '.encoded') assert fsize('target/'+file + '.encoded.decoded') == fsize('data/'+file), file with open('target/'+file + '.encoded.decoded', 'r') as fp: with open('data/'+file, 'r') as fp2: assert fp.read() == fp2.read() except: print 'error in', file raise print_separator()
def perform_operations(message_body,message_length_size,message_type_size,conn) : #print "Just Echoing the message back to the client after verification of signature" payload_length = long(message_body[0:message_length_size]) signed_digest_length = long(message_body[message_length_size:2*message_length_size]) message_type = message_body[2*message_length_size:2*message_length_size + message_type_size] payload = message_body[2*message_length_size + message_type_size :2*message_length_size+ message_type_size + payload_length] signed_digest = long(message_body[2*message_length_size + payload_length + message_type_size:]) h = SHA256.new() h.update(payload) computed_message_digest = h.hexdigest() input_tuple = (signed_digest,None) global total_number_of_adds global max_no_of_adds global flush_in_progress while flush_in_progress == 1 : pass if rsapubkey.verify(computed_message_digest,input_tuple) == True : print "Server : Signature Verification of the received message suceeded" if message_type == '01' : # ADD command print "Switched to ADD mode. Waiting for key@file_data ... " data = payload split_list = data.split('@') key = split_list[0] file_data_string = split_list[1] base_filename_to_store = key + ".txt" insert_command = "INSERT INTO " + TABLE_NAME + " SET " + "Timestamp=" + '"' + key + '"' + "," + " filename=" + '"' + key + ".txt" + '"' + ";" db = MySQLdb.connect(host="127.0.0.1", user= user_name, passwd= passwd, db=DATABASE_NAME) # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() #print "Insert command = ", insert_command cur.execute(insert_command) db.commit() db.close() encode(k=k,m=m,data_to_encode=file_data_string,base_filename_to_store = base_filename_to_store,ec_type = ec_type) #total_number_of_adds = total_number_of_adds + 1 #if total_number_of_adds >= max_no_of_adds : # total_number_of_adds = 0 # flush_all() conn.sendall("OK") elif message_type == '02' : #RETRIEVE Command #print "Switched to retrieve mode. Waiting for retrieve key ... " key = payload #print "Received key = ", key retrieve_command = "SELECT * FROM " + TABLE_NAME + " WHERE Timestamp=" + '"' + key + '";' #print "retrieve_command = ", retrieve_command db = MySQLdb.connect(host="127.0.0.1", user= user_name, passwd= passwd, db=DATABASE_NAME) # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() cur.execute(retrieve_command) db.commit() db.close() # print all the first cell of all the rows decoded_data_list = [] #print "Result of command = " for row in cur.fetchall() : #print "Row = ", row # row should be file name to decode and fetch decoded_data = decode(k,m,row[1],ec_type) decoded_data_list.append(decoded_data) #print "Done" #print "Decoded data for transmission = " for entry in decoded_data_list : if entry == -1 : conn.sendall("-1") else : print entry #conn.sendall(entry) send_message(conn,entry,"OK") if len(decoded_data_list) == 0 : conn.sendall("-2") return
import encoder as e #import decoder as d import table as t testMessage = "This is a test message 123456789 .. ,, .. ,, " encodedString = e.encode(testMessage) print encodedString #print d.decode(encodedString)
def test_encode_bytes(self): self.assertEqual(self.correct_bytes_obj, encode(self.bytes_obj, self.mapping))