def get_test_accounts_from_args(argv): node_account_id = argv[1] pk = argv[2] sk = argv[3] rpc_nodes = argv[4].split(',') num_nodes = int(argv[5]) max_tps = float(argv[6]) logger.info(f'rpc_nodes: {rpc_nodes}') node_account_key = key.Key(node_account_id, pk, sk) test_account_keys = [ key.Key(mocknet.load_testing_account_id(node_account_id, i), pk, sk) for i in range(mocknet.NUM_ACCOUNTS) ] base_block_hash = mocknet_helpers.get_latest_block_hash() rpc_infos = [(rpc_addr, mocknet_helpers.RPC_PORT) for rpc_addr in rpc_nodes] node_account = account.Account(node_account_key, mocknet_helpers.get_nonce_for_pk( node_account_key.account_id, node_account_key.pk), base_block_hash, rpc_infos=rpc_infos) accounts = [ account.Account(key, mocknet_helpers.get_nonce_for_pk( key.account_id, key.pk), base_block_hash, rpc_infos=rpc_infos) for key in test_account_keys ] max_tps_per_node = max_tps / num_nodes return node_account, accounts, max_tps_per_node
def get_test_accounts_from_args(argv): assert len(argv) == 7 node_account_id = argv[1] pk = argv[2] sk = argv[3] assert argv[4] rpc_nodes = argv[4].split(',') logger.info(f'rpc_nodes: {rpc_nodes}') max_tps = float(argv[5]) need_deploy = (argv[6] == 'deploy') logger.info(f'need_deploy: {need_deploy}') rpc_infos = [(rpc_addr, mocknet_helpers.RPC_PORT) for rpc_addr in rpc_nodes] node_account_key = key_mod.Key(node_account_id, pk, sk) test_account_keys = [ key_mod.Key(load_testing_account_id(node_account_id, i), pk, sk) for i in range(NUM_ACCOUNTS) ] base_block_hash = mocknet_helpers.get_latest_block_hash() node_account = account_mod.Account(node_account_key, mocknet_helpers.get_nonce_for_pk( node_account_key.account_id, node_account_key.pk), base_block_hash, rpc_infos=rpc_infos) if need_deploy: init_ft(node_account) accounts = [] for key in test_account_keys: account = account_mod.Account(key, mocknet_helpers.get_nonce_for_pk( key.account_id, key.pk), base_block_hash, rpc_infos=rpc_infos) accounts.append(account) if need_deploy: logger.info(f'Deploying contract for account {key.account_id}') tx_res = account.send_deploy_contract_tx('betanet_state.wasm') logger.info(f'Deploying result: {tx_res}') init_ft_account(node_account, account) logger.info( f'Account {key.account_id} balance after initialization: {account.get_amount_yoctonear()}' ) mocknet_helpers.wait_at_least_one_block() return node_account, accounts, max_tps
def addKey(self, levelKey): for key1 in levelKey: block = key.Key(key1[0], key1[1]) block.rect.x = key1[2] block.rect.y = key1[3] block.player = self.player self.key_list.add(block)
def create_key(algo): dct = key.Key() obj = Crypto.Random.random.StrongRandom() choice = obj.randint(1,3) if algo == "AES": dct.algorithm="AES" dct.blocksize=16 if choice == 1: dct.keysize=128 elif choice == 2: dct.keysize=196 else: dct.keysize=256 if algo == "Blowfish": dct.algorithm="Blowfish" dct.blocksize=8 if choice == 1: dct.keysize=128 elif choice == 2: dct.keysize=196 else: dct.keysize=256 if algo == "CAST": dct.algorithm="CAST" dct.blocksize=8 if choice == 1: dct.keysize=40 elif choice == 2: dct.keysize=80 else: dct.keysize=128 if algo == "RC5": dct.algorithm="RC5" dct.blocksize=8 if choice == 1: dct.keysize=128 elif choice == 2: dct.keysize=196 else: dct.keysize=512 if algo == "DES": dct.algorithm="DES" dct.blocksize=8 dct.keysize=64 if algo == "DES3": dct.algorithm="DES3" dct.blocksize=8 dct.keysize=128 if algo == "IDEA": dct.algorithm="IDEA" dct.blocksize=8 dct.keysize=128 if algo == "none": dct.algorithm="none" dct.keysize=8 dct.keystring= binascii.hexlify(Crypto.Random.get_random_bytes(int(dct.keysize / 8))) if dct.algorithm == "none": dct=None return dct
def __init__(self, width, height, title): super().__init__(width, height, title) # Call the parent class's init function self.song = song.Song() self.listOfKeys = [] for i in range(1, 4): self.listOfKeys.append(key.Key(i))
def find_key_id(key_id, active_key, accept_keys): if active_key and active_key.key_id == key_id: return active_key if accept_keys is not None: for accept_key in accept_keys: if accept_key.key_id == key_id: return accept_key if key_id == 0 and active_key is None and (accept_keys is None or accept_keys == []): return key.Key(0, "null", None) return None
def makeBoard(self): # board should be [x][y] self.tiles = [[tile.Tile("empty") for y in range(self.height)] for x in range(self.width)] # populate static objects: walls, lava, and exit if "walls" in self.levelData: for wall in self.levelData["walls"]: x = wall["position"][0] y = wall["position"][1] self.tiles[x][y].type = "wall" if "deathTiles" in self.levelData: for deathTile in self.levelData["deathTiles"]: x = deathTile["position"][0] y = deathTile["position"][1] self.tiles[x][y].type = "lava" exitX = self.levelData["exit"]["position"][0] exitY = self.levelData["exit"]["position"][1] self.tiles[exitX][exitY].type = "exit" # Need to figure out how wormholes will be stored if "wormholes" in self.levelData: for wormhole in self.levelData["wormholes"]: entranceX = wormhole["positionEntrance"][0] entranceY = wormhole["positionEntrance"][1] exitX = wormhole["positionExit"][0] exitY = wormhole["positionExit"][1] entranceDirection = wormhole["directionEntrance"] exitDirection = wormhole["directionExit"] self.tiles[exitX][exitY] = portalExit.PortalExit(exitX, exitY, exitDirection) self.tiles[entranceX][entranceY] = portal.Portal(entranceDirection, self.tiles[exitX][exitY]) self.wormholes.append(self.tiles[entranceX][entranceY]) # populate keys if "keys" in self.levelData: for keyObj in self.levelData["keys"]: x = keyObj["startingPosition"][0] y = keyObj["startingPosition"][1] xmin = keyObj["positionBoundsX"][0] xmax = keyObj["positionBoundsX"][1] ymin = keyObj["positionBoundsY"][0] ymax = keyObj["positionBoundsY"][1] self.tiles[x][y].key = True self.keys.append(key.Key(x, y, xmin, xmax, ymin, ymax))
def create_score_object(path, use_images=False, composer='noname', title='unknown'): count = len(os.listdir(path)) if use_images: i_a.convert_images_to_textfile(count, path) measure_arrays = f_a.get_data_from_file() d_a.search_for_incorrect_measures(measure_arrays) key1 = (d_a.get_key(measure_arrays)) key.Key(key1) score_object = score.Score(key1, composer, title) bass_part_object = part.Part('bass') treble_part_object = part.Part('treble') previous_measures = [None, None] # 0: Left, 1: Right for index, measure in enumerate(measure_arrays): #print(str(index) + ': ' + str(len(measure))) if index == len(measure_arrays) - 1: tied_notes = [] else: tied_notes = d_a.analyze_for_ties(measure, measure_arrays[index + 1]) temp = d_a.analyze_pressed_keys(measure) bass_measure_part = temp[0] treble_measure_part = temp[1] temp = c_m.abc_both_hands(bass_measure_part, treble_measure_part, len(measure), tied_notes, previous_measures) bass_measure_object = temp[0] treble_measure_object = temp[1] bass_part_object.add(bass_measure_object) treble_part_object.add(treble_measure_object) previous_measures = [bass_measure_object, treble_measure_object] # 0: Left, 1: Right score_object.add([treble_part_object, bass_part_object]) return score_object
def docomo(_utt, _context): url = "https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY=" # api_key = "5534676c4151462f5875467370787576482e694538337a6864674e5255454a54552f62355866496a414730" key_class = key.Key() api_key = key_class.api if _context is None: context = "" else: context = _context method = "POST" headers = {"Content-Type": "application/json"} mode = "dialog" utt = _utt obj = {"utt": _utt, "mode": mode, "context": context} json_data = json.dumps(obj).encode("utf-8") request = urllib.request.Request(url + api_key, data=json_data, method=method, headers=headers) with urllib.request.urlopen(request) as response: response_body = response.read().decode("utf-8") # print(response_body) json_obj = json.loads(response_body) keylist = json_obj.keys() for k in keylist: if k == "utt": _utt = (json_obj[k]) print(json_obj[k]) if k == "context": _context = (json_obj[k]) # docomo(json_obj[k]) else: subprocess.call("zunko/echoseika.exe -cv ZUNKO_EX " + _utt) _utt = input() if (_utt == "ばいばい"): return docomo(_utt, _context)
def create_keylist(): entry = [ "ctrl", "alt", "bksp", "down", "up", "left", "right", "enter", "esc", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "shift", "home", "ins", "help", "numlck", "pagedown", "pageup", "tab", "scrlock" ] symbol = [ "^", "%", "{BACKSPACE}", "{DOWN}", "{UP}", "{LEFT}", "{RIGHT}", "{ENTER}", "{ESC}", "{F1}", "{F2}", "{F3}", "{F4}", "{F5}", "{F6}", "{F7}", "{F8}", "{F9}", "{F10}", "{F11}", "{F12}", "{F13}", "{F14}", "{F15}", "{F16}", "+", "{HOME}", "{INSERT}", "{HELP}", "{NUMLOCK}", "{PGDN}", "{PGUP}", "{TAB}", "{SCROLLLOCK}" ] keylist = [] for x in range(0, len(entry)): shortcut_key = key.Key(entry[x], symbol[x]) keylist.append(shortcut_key) return keylist
args = parser.parse_args() assert args.ips ips = args.ips.split(',') assert args.accounts account_ids = args.accounts.split(',') assert len(account_ids) == len( ips), 'List of test accounts must match the list of node IP addresses' interval_sec = args.interval_sec assert interval_sec > 1, 'Need at least 1 second between pings' port = args.port pk, sk = args.public_key, args.private_key rpc_server = (args.rpc_server_addr, args.rpc_server_port) keys = [key_mod.Key(account_id, pk, sk) for account_id in account_ids] base_block_hash = mocknet_helpers.get_latest_block_hash(addr=rpc_server[0], port=rpc_server[1]) accounts = [] for ip, key in zip(ips, keys): nonce = mocknet_helpers.get_nonce_for_pk(key.account_id, key.pk, addr=rpc_server[0], port=rpc_server[1]) accounts.append( account_mod.Account(key, nonce, base_block_hash, rpc_infos=[(ip, port)])) prometheus_client.start_http_server(args.metrics_port)
def test_init_decryption(self): key_to_encrypt = { 'a': 'q', 'b': 'v', 'c': 'x', 'd': 'z', 'e': 'y', 'f': 'w', 'g': 'u', 'h': 't', 'i': 's', 'j': 'r', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'r': 'j', 's': 'i', 't': 'h', 'u': 'g', 'w': 'f', 'y': 'e', 'z': 'd', 'x': 'c', 'v': 'b', 'q': 'a', 'A': 'Q', 'B': 'V', 'C': 'X', 'D': 'Z', 'E': 'Y', 'F': 'W', 'G': 'U', 'H': 'T', 'I': 'S', 'J': 'R', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'R': 'J', 'S': 'I', 'T': 'H', 'U': 'G', 'W': 'F', 'Y': 'E', 'Z': 'D', 'X': 'C', 'V': 'B', 'Q': 'S', '1': '5', '2': '9', '3': '8', '4': '7', '5': '6', '6': '4', '7': '3', '8': '2', '9': '1', '.': ',', ',': '.', ':': ';', ';': ':', '?': '!', '!': '?', '-': '_', '_': '-', '(': ')', ')': '(', '%': '$', '$': '%', ' ': '&', '&': ' ', '+': '*', '*': '+' } k1 = key.Key(key_to_encrypt) reversed_key = k1.createReverseKey() encrypted_text = 'Lmy&nljmsmu.&ftym&Ujyulj&Iqniq&flpy&wjln&hjlgvoyz&zjyqni.' e1 = decryption.Decryption(reversed_key, encrypted_text) mess = 'Given object is not instance of Decryption' self.assertIsInstance(e1, decryption.Decryption, mess)
def main(): # Set up the commandline arguments parser = argparse.ArgumentParser() parser.add_argument("-i", "--infile", required=True, help="ciphertext input file") parser.add_argument("-o", "--outfile", help="output file") parser.add_argument("-d", "--dictionary", default='dictionary.txt', help="dictionary file") parser.add_argument("-c", "--crib", default='cribwords.txt', help="cribwords file") parser.add_argument("-s", "--stripciphertext", action="store_true", help="should we strip the ciphertext of spaces and" "punctuation before we start to attempt decode") # Parse the commandline arguments args = parser.parse_args() outtext = '' ciphertext = '' # Read in the ciphertext` if args.infile is not None: with open(args.infile, 'r') as f: for line in f: ciphertext += line # Strip if requested if args.stripciphertext: ciphertext = stripciphertext(ciphertext) # Initialise the key k = key.Key() # Do the frequency analysis freq = frequency.frequency() freq.add(ciphertext) freqlist = freq.freq_list() print(str(freqlist)) # Assume e is the most frequent and t is the second most frequent letters c, n = freqlist[0] k.set(c, 'e', 'Frequency') e = c c, n = freqlist[1] k.set(c, 't', "Frequency") t = c # Now we know 't' and 'e', try to find the h from 'the' c, n = freq.h_spotter(t, e, ciphertext) k.set(c, 'h', 'h spotter') # get the partially decrypted ciphertext pd = k.decipher(ciphertext) # Use the cribs to try and get a start on the cracking crib = Crib() crib.load(args.crib) frequent_hits, hits = crib.search2(ciphertext) for cribword in frequent_hits: for match in frequent_hits[cribword]: score = frequent_hits[cribword][match] / len(hits[cribword]) if score > 0.1: k.set_string(match, cribword, "Cribword: " + cribword) outtext += str(hits) + '\n' outtext += str(frequent_hits) + '\n' for cribword in frequent_hits: outtext += cribword + '\n' for match in frequent_hits[cribword]: score = frequent_hits[cribword][match]/len(hits[cribword]) outtext += '\t' + match + ":\t " + str(score) + '\n' outtext += '\n\n' + k.decipher(ciphertext) + '\n\n' outtext += '\n' + str(k.key) + '\n' outtext += '\n' + str(k.history) + '\n' if args.outfile is not None: with open(args.outfile, 'w') as f: f.write(outtext) else: print(outtext)
import key,codecs,math msg = [char for char in open('flag.txt','r').read()] a,b,c = key.Key() try: d11 = 4*a*c d1 = b**2 - d11 d = math.sqrt(d1) r11 = 2*a r1 = (-b + d)/r11 r2 = (-b - d)/r11 except: print("No possible solution") for char in enumerate(msg): if(char[0] % 2 == 0): msg[char[0]] = chr(ord(msg[char[0]]) ^ int(r1)) else: msg[char[0]] = chr(ord(msg[char[0]]) ^ int(r2)) print(codecs.encode(''.join(msg).encode(),'hex').decode())
def get_test_accounts_from_args(argv): node_account_id = argv[1] pk = argv[2] sk = argv[3] assert argv[4] rpc_nodes = argv[4].split(',') logger.info(f'rpc_nodes: {rpc_nodes}') num_nodes = int(argv[5]) max_tps = float(argv[6]) leader_account_id = sys.argv[7] upk = sys.argv[8] usk = sys.argv[9] node_account_key = key.Key(node_account_id, pk, sk) test_account_keys = [ key.Key(mocknet.load_testing_account_id(node_account_id, i), pk, sk) for i in range(mocknet.NUM_ACCOUNTS) ] base_block_hash = mocknet_helpers.get_latest_block_hash() rpc_infos = [(rpc_addr, mocknet_helpers.RPC_PORT) for rpc_addr in rpc_nodes] node_account = account.Account(node_account_key, mocknet_helpers.get_nonce_for_pk( node_account_key.account_id, node_account_key.pk), base_block_hash, rpc_infos=rpc_infos) accounts = [ account.Account(key, mocknet_helpers.get_nonce_for_pk( key.account_id, key.pk), base_block_hash, rpc_infos=rpc_infos) for key in test_account_keys ] max_tps_per_node = max_tps / num_nodes special_account_keys = [ key.Key(mocknet.SKYWARD_ACCOUNT, upk, usk), key.Key(mocknet.TOKEN1_ACCOUNT, upk, usk), key.Key(mocknet.TOKEN2_ACCOUNT, upk, usk), key.Key(mocknet.ACCOUNT1_ACCOUNT, upk, usk), key.Key(mocknet.TOKEN2_OWNER_ACCOUNT, upk, usk), ] global special_accounts special_accounts = [ account.Account(key, mocknet_helpers.get_nonce_for_pk( key.account_id, key.pk), base_block_hash, rpc_infos=rpc_infos) for key in special_account_keys ] start_time = time.monotonic() if node_account_id == leader_account_id: initialize_skyward_contract(node_account_id, pk, sk) elapsed = time.monotonic() - start_time if elapsed < SKYWARD_INIT_TIME: logger.info(f'Leader sleeps for {SKYWARD_INIT_TIME-elapsed}sec') time.sleep(SKYWARD_INIT_TIME - elapsed) else: logger.info(f'Non-leader sleeps for {SKYWARD_INIT_TIME}sec') time.sleep(SKYWARD_INIT_TIME) return node_account, accounts, max_tps_per_node
def main2(): # Set up the commandline arguments parser = argparse.ArgumentParser() parser.add_argument("-i", "--infile", required=True, help="ciphertext input file") parser.add_argument("-o", "--outfile", help="output file") parser.add_argument("-d", "--dictionary", default='dictionary.txt', help="dictionary file") parser.add_argument("-c", "--crib", default='cribwords.txt', help="cribwords file") parser.add_argument("-r", "--reverse", action="store_true", help="Reverse the ciphertext before decryption") parser.add_argument("-s", "--stripciphertext", action="store_true", help="should we strip the ciphertext of spaces and" "punctuation before we start to attempt decode") parser.add_argument("-t", "--cribthreshold", default=0.1, help="Thresholds for us to use the cribwords", type=float) # Parse the commandline arguments args = parser.parse_args() outtext = '' ciphertext = '' # Read in the ciphertext` if args.infile is not None: with open(args.infile, 'r') as f: for line in f: ciphertext += line # Reverse the ciphertext if wanted if args.reverse: ciphertext = ciphertext[::-1] # Strip if requested if args.stripciphertext: ciphertext = stripciphertext(ciphertext) # Initialise the key k = key.Key() # Do the frequency analysis freq = frequency.frequency() freq.add(ciphertext) freqlist = freq.freq_list() print(str(freqlist)) # Assume e is the most frequent and t is the second most frequent letters #c, n = freqlist[0] #k.set(c, 'e', 'Frequency') #e = c #c, n = freqlist[1] #k.set(c, 't', "Frequency") #t = c # Now we know 't' and 'e', try to find the h from 'the' #c, n = freq.h_spotter(t, e, ciphertext) #k.set(c, 'h', 'h spotter') # Use the cribs to try and get a start on the cracking crib = Crib() crib.load(args.crib) frequent_hits, hits = crib.search2(ciphertext) for cribword in frequent_hits: for match in frequent_hits[cribword]: score = frequent_hits[cribword][match] / len(hits[cribword]) if score > args.cribthreshold: k.set_string(match, cribword, "Cribword: " + cribword) # get the partially decrypted ciphertext print(k.decipher(ciphertext)) # put the loop in a try block so that if we hit an Exception # we will save the state of the key and ciphertext... try: # Start an interactive loops while True: cmd = input("\n:> ") # Check to see whether we entered an integer try: # If so then lets use it to # go back in time... i = int(cmd) k.history = i except: if len(cmd) == 1: if cmd.upper() in ENCODE_CHARS: p = input("Plaintext :> ") k.set(cmd, p, 'User') elif cmd == '?': help() elif cmd == 'key': print('\n' + str(k.key) + '\n') elif cmd == 'freq': print(str(freqlist)) elif cmd == 'quit': break elif cmd == 'history': print(k.history) elif cmd == 'crib': frequent_hits, hits = crib.search2(k.decipher(ciphertext)) print('\n' + str(hits)) print('\n' + str(frequent_hits)) elif cmd == 'help': help() print('\n' + k.decipher(ciphertext)) finally: outtext = '' for cribword in frequent_hits: outtext += cribword + '\n' for match in frequent_hits[cribword]: score = frequent_hits[cribword][match]/len(hits[cribword]) outtext += '\t' + match + ":\t " + str(score) + '\n' outtext += '\n\n' + k.decipher(ciphertext) + '\n\n' outtext += '\n' + str(k.key) + '\n' outtext += '\n' + str(k.history) + '\n' if args.outfile is not None: with open(args.outfile, 'w') as f: f.write(outtext) else: print(outtext)
def post(self): now = datetime.datetime.now() form = GetOrganizationForm(self.request.POST) if not form.validate(): self.redirect('/authentication') event = None for e in event_db.Event.gql( "WHERE name = :name LIMIT 1", name = form.event.data): event = e # check org and incident match org = None selected_org_name = self.request.get("name") if selected_org_name == "Admin": # admin user for x in organization.Organization.gql( "WHERE name = :name LIMIT 1", name=selected_org_name ): org = x else: # regular user for x in organization.Organization.gql( "WHERE name = :name AND incidents = :incident LIMIT 1", name=selected_org_name, incident=event.key() ): org = x if org is None: # try legacy incident field for x in organization.Organization.gql( "WHERE name = :name and incident = :incident LIMIT 1", name=selected_org_name, incident=event.key() ): org = x # handle verified+active existing org joining new incident if not org and selected_org_name == 'Other': existing_org_name = self.request.get("existing-organization") for x in organization.Organization.gql( "WHERE name = :name LIMIT 1", name=existing_org_name): org = x if event and org and org.password == form.password.data: # login was successful # (temp) force migration of org.incident -> org.incidents unicode(org.incidents) # add org to incident if not already allowed if not org.may_access(event): org.join(event) logging.info( u"authentication_handler: " u"Existing organization %s has joined incident %s." % ( org.name, event.name ) ) # email administrators review_url = "%s://%s/admin-single-organization?organization=%s" % ( urlparse(self.request.url).scheme, urlparse(self.request.url).netloc, org.key().id() ) organization_form = organization.OrganizationForm(None, org) email_administrators_using_templates( event=event, subject_template_name='organization_joins_incident.to_admins.subject.txt', body_template_name='organization_joins_incident.to_admins.body.txt', organization=org, review_url=review_url, organization_form=organization_form, ) org.save() # timestamp login now = datetime.datetime.utcnow() org.timestamp_login = now org.save() event.timestamp_last_login = now event.save() # create login key keys = key.Key.all() keys.order("date") selected_key = None for k in keys: age = now - k.date # Only use keys created in about the last day, # and garbage collect keys older than 2 days. if age.days > 14: k.delete() elif age.days <= 1: selected_key = k if not selected_key: selected_key = key.Key( secret_key = ''.join(random.choice( string.ascii_uppercase + string.digits) for x in range(20))) selected_key.put() # set cookie of org and event self.response.headers.add_header("Set-Cookie", selected_key.getCookie(org, event)) self.redirect(urllib.unquote(self.request.get('destination', default_value='/').encode('ascii'))) else: self.redirect(self.request.url + "?error_message=Incorrect Organization and Passcode Combination")
'!': '?', '-': '_', '_': '-', '(': ')', ')': '(', '%': '$', '$': '%', ' ': '&', '&': ' ', '+': '*', '*': '+' } #reading txt file where is the text for encryption with open('kafka.txt') as file: text_for_encryption = file.read() k1 = key.Key(key_to_encrypt) reversed_key = k1.createReverseKey() e1 = encryption.Encryption(key_to_encrypt, text_for_encryption) encrypted_text = e1.encrypt() print(encrypted_text) #saving encrypted message to txt file with open('encrypted.txt', 'w') as file: file.write(encrypted_text) #d1 = decryption.Decryption(reversed_key, encrypted_text) #print(d1.decrypt())
def create_key(self, key_config): key_id = key_config["id"] algorithm = key_config["algorithm"] secret = key_config["secret"] self.keys[key_id] = key.Key(key_id, algorithm, secret)
def test_init_key(self): key_to_encrypt = { 'a': 'q', 'b': 'v', 'c': 'x', 'd': 'z', 'e': 'y', 'f': 'w', 'g': 'u', 'h': 't', 'i': 's', 'j': 'r', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'r': 'j', 's': 'i', 't': 'h', 'u': 'g', 'w': 'f', 'y': 'e', 'z': 'd', 'x': 'c', 'v': 'b', 'q': 'a', 'A': 'Q', 'B': 'V', 'C': 'X', 'D': 'Z', 'E': 'Y', 'F': 'W', 'G': 'U', 'H': 'T', 'I': 'S', 'J': 'R', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'R': 'J', 'S': 'I', 'T': 'H', 'U': 'G', 'W': 'F', 'Y': 'E', 'Z': 'D', 'X': 'C', 'V': 'B', 'Q': 'S', '1': '5', '2': '9', '3': '8', '4': '7', '5': '6', '6': '4', '7': '3', '8': '2', '9': '1', '.': ',', ',': '.', ':': ';', ';': ':', '?': '!', '!': '?', '-': '_', '_': '-', '(': ')', ')': '(', '%': '$', '$': '%', ' ': '&', '&': ' ', '+': '*', '*': '+' } k1 = key.Key(key_to_encrypt) mess = 'Given object is not instance of Key' self.assertIsInstance(k1, key.Key, mess)
def __init__(self, passive_nodes, run_which_nodes, interactive, telnet_port_file, ipv4_multicast_loopback, ipv6_multicast_loopback, log_level, config): # pylint:disable=too-many-statements log_file_name = "rift.log" # TODO: Make this configurable if "RIFT_TEST_RESULTS_DIR" in os.environ: log_file_name = os.environ[ "RIFT_TEST_RESULTS_DIR"] + "/" + log_file_name logging.basicConfig( filename=log_file_name, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', level=log_level) self._run_which_nodes = run_which_nodes self._interactive = interactive self._telnet_port_file = telnet_port_file self.ipv4_multicast_loopback = ipv4_multicast_loopback self.ipv6_multicast_loopback = ipv6_multicast_loopback self._config = config if self.nr_nodes() > 1: self._stand_alone = False self.simulated_interfaces = True self.physical_interface_name = self.default_physical_interface() else: self._stand_alone = True self.simulated_interfaces = False self.physical_interface_name = None self.tx_src_address = self.read_global_configuration( config, 'tx_src_address', '') self.floodred_enabled = self.read_global_configuration( config, 'flooding_reduction', True) self.floodred_redundancy = self.read_global_configuration( config, 'flooding_reduction_redundancy', constants.DEFAULT_FLOODING_REDUCTION_REDUNDANCY) self.floodred_similarity = self.read_global_configuration( config, 'flooding_reduction_similarity', constants.DEFAULT_FLOODING_REDUCTION_SIMILARITY) self.floodred_system_random = random.randint(0, 0xffffffffffffffff) self.intf_traffic_stats_group = stats.Group() self.intf_security_stats_group = stats.Group() self.intf_lie_fsm_stats_group = stats.Group() self.node_ztp_fsm_stats_group = stats.Group() self.keys = {} # Indexed by key-id self.keys[0] = key.Key(key_id=0, algorithm="null", secret="") self._nodes = sortedcontainers.SortedDict() self.create_configuration(passive_nodes) cli_log = logging.getLogger('cli') if self._nodes: first_node = self._nodes.peekitem(0)[1] else: first_node = None if self._interactive: make_terminal_unbuffered() self._cli_listen_handler = None self._interactive_cli_session_handler = cli_session_handler.CliSessionHandler( sock=None, rx_fd=sys.stdin.fileno(), tx_fd=sys.stdout.fileno(), parse_tree=self.parse_tree, command_handler=self, log=cli_log, node=first_node) else: self._cli_listen_handler = cli_listen_handler.CliListenHandler( command_tree=self.parse_tree, command_handler=self, log=cli_log, default_node=first_node) self._interactive_cli_session_handler = None if self._telnet_port_file is None: print( "Command Line Interface (CLI) available on port {}".format( self._cli_listen_handler.port)) else: try: with open(self._telnet_port_file, 'w') as file: print(self._cli_listen_handler.port, file=file) except IOError: pass # TODO: Log an error