def info(self, msg, flag=None): if flag: return huepy.good("{0} {1}".format(flag, msg)) else: return huepy.good(msg)
def main(): ########## # Step 1 # ########## # Get public urls for each episode using requests, and save all data to a local file. # capitol_links = get_capitol_links() # old method saved_data = read_json_data() if len(saved_data) == 73: print(info("using saved data")) capitols = saved_data print(info(f"{len(capitols)} 'capitols' available")) else: print(info("getting 'capitols' from CCMA API...")) capitols = get_capitols_api() save_json_data(capitols) print(good(f"{len(capitols)} 'capitols' saved")) ########## # Step 2 # ########## # Obtain the hidden mp4 url of each episode. for capitol in capitols: url_mp4 = None try: if not capitol["url_mp4"]: # url_mp4 = selenium_parse(capitol["url"]) # old method using selenium url_mp4 = get_mp4_link_api(capitol["id"]) else: print(good(f"capitol {capitol['capitol']} url_mp4 ok")) continue except KeyError: # url_mp4 = selenium_parse(capitol["url"]) # old method using selenium url_mp4 = get_mp4_link_api(capitol["id"]) if url_mp4: capitol["url_mp4"] = url_mp4 print(good(f"capitol {capitol['capitol']} url_mp4 ok")) save_json_data(capitols) print(info("data updated")) else: print(bad(f"error with url_mp4 capitol {capitol['capitol']}")) ########## # Step 3 # ########## # Download mp4 videos with wget for capitol in capitols: try: if capitol["url_mp4"]: download_mp4(capitol) except KeyError: pass
def download_mp4(capitol): # Create save directory save_dir = Path("capitols") try: save_dir.mkdir() except FileExistsError: pass file_name = Path(f"{capitol['nom_friendly']}.mp4") if (save_dir / file_name).exists(): print(good(f"{file_name} already exists")) else: print(run(f"Downloading {file_name}")) wget.download(capitol["url_mp4"], str(save_dir / file_name)) print() print(good(f"{file_name} correctly downloaded"))
def _post_epoch(engine): lr_scheduler.step() if is_main_process(): save_name = osp.join(args.path, 'checkpoint.pth') save_checkpoint({ 'epoch': engine.state.epoch, 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict() }, save_name) print(hue.good('save model: {}'.format(save_name)))
def resume_from_checkpoint(args, model, optimizer=None, lr_scheduler=None): load_name = args.resume checkpoint = torch.load(load_name) args.train.start_epoch = checkpoint['epoch'] model.load_state_dict(checkpoint['model']) if optimizer is not None: optimizer.load_state_dict(checkpoint['optimizer']) if lr_scheduler is not None: lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) print(hue.good('loaded checkpoint %s' % (load_name))) print(hue.info('model was trained for %s epochs' % (args.train.start_epoch))) return args, model, optimizer, lr_scheduler
def main(): if args.config: initial_config(config_complete_path) check_settings() config = ConfigParser() config.read(config_complete_path) auth = tweepy.OAuthHandler(config['API'].get('ConsumerKey', None), config['API'].get('ConsumerSecret', None)) username = args.user if username in config: access_token = config[username].get('AccessToken', None) access_secret = config[username].get('AccessSecret', None) else: print( 'The username inputted was not found in my registry. Let\'s configure it!' ) access_token, access_secret = user_config(config_complete_path, auth) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth, wait_on_rate_limit=True) twitter_api_auth = { 'consumer_key': auth.consumer_key, 'consumer_secret': auth.consumer_secret, 'access_token': access_token, 'access_token_secret': access_secret, } bom = create_botometer(config['API'].get('MashapeKey', None), twitter_api_auth) allowlist_path = config['Global'].get( 'AllowListPath', pathjoin(config_path, 'AllowList.pickle')) followers = filter_followers(allowlist_path, get_followers_twint(username)) # followers = filter_followers(allowlist_path, get_followers(api, username)) level = args.level while_block = Block(args.noblock, args.softblock, args.report) bots, non_bots = identify_bots(api, bom, followers, level, while_block) if not while_block.block_now: print('Should I block accounts identified as bots now?') post_block = Block(confirm(), args.softblock, args.report) block_bots(api, bots, post_block) if while_block.block_now or post_block.block_now: print(bad('{} bot accounts blocked!'.format(len(bots)))) if args.saveallowlist: add_to_allowlist(allowlist_path, non_bots) print( good('{} non-bot accounts added to the allowlist!'.format( len(non_bots))))
def validate(html, url, bot): sec = "VALIDATE" good_message = "You have successfully posted your ad!" if good_message in html: logging.info(f"{sec} - Ad was created succesfully") logging.info(f"{sec} - Ad URL: {url}") print(good("Ad was posted succesfully")) print(info(f"Ad URL: {url}")) else: logging.info(f"{sec} - Failed posting ad, dump file on server.") print(bad("There was an error posting the ad. Dumping HTML file.")) dump_html(html) bot.get_screenshot_as_file('output.png')
def substitute_word(word, text, sound): print(REX.sub(r'\1[...]\3', text)) guess = input('> ') if guess.lower() == REX.search(text).groups()[1].lower(): print(huepy.good("it's right!")) elif guess.lower() == word.info.text.lower(): print(huepy.info("right word, wrong form")) else: # https://youtu.be/oFlUCr42qzI print(huepy.bad("wrong!")) play(sound) print(text) input()
def _post_epoch(engine): if is_main_process(): save_name = osp.join(args.path, 'checkpoint.pth') save_checkpoint( { 'epoch': engine.state.epoch, 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict() }, save_name) print(hue.good('save model: {}'.format(save_name))) tfboard.export_scalars_to_json( osp.join(args.path, 'all_scalar.json'))
def login(self, username, password): sec = "LOGIN" bot = self.bot self.username = username self.password = password bot.get("https://www.kijiji.ca/t-login.html") uname_field = bot.find_element_by_id("LoginEmailOrNickname") uname_field.send_keys(self.username) pword_feild = bot.find_element_by_id('login-password') pword_feild.send_keys(self.password) bot.find_element_by_xpath('//*[@id="SignInButton"]').click() time.sleep(5) # If we're logged in, the text "Register should not be visible" assert "Register" not in bot.page_source, "Failed to login." print(good(f"Succesfully logged into {self.username}")) logging.info(f"{sec} - We're logged in to: {self.username}")
def load_NAE_weights(args, model): if args.dataset == 'CUHK-SYSU': model_path = 'logs/cuhk-sysu/checkpoint.pth' elif args.dataset == 'PRW': model_path = 'logs/prw/checkpoint.pth' checkpoint = torch.load(model_path) state_dict = checkpoint['model'] state_dict['roi_heads.embedding_head.projectors.feat_res4.0.weight'] = \ state_dict['roi_heads.embedding_head.projectors.feat_res4.0.weight'].view( 128, 1024, 1, 1) state_dict['roi_heads.embedding_head.projectors.feat_res5.0.weight'] = \ state_dict['roi_heads.embedding_head.projectors.feat_res5.0.weight'].view( 128, 2048, 1, 1) model.load_state_dict(state_dict) print(hue.good('NAE pre-trained weights loaded.')) return model
def connect(self, host, port, name, user, password): self.hashobject.update(password.encode('utf-8')) try: self.socket.connect((host, port)) print(huepy.run('Successfully connected')) self.socket.send( str({ 'type': 'login', 'database': str(name), 'user': str(user), 'password': self.hashobject.hexdigest() }).encode('utf-8')) except: print( huepy.bad( 'Connection failed, please check the network or address')) return False returnValue = dict(eval(self.socket.recv(3012))) if returnValue['type'] == 'error': if returnValue['state'] == '404': print( huepy.bad( 'Connection failed, please check the address or databasename' )) return False elif returnValue['state'] == '1304': print( huepy.bad( 'Connection failed, please check the username or password' )) return False else: print(huepy.bad('Connection failed')) return False elif returnValue['type'] == 'token': self.Token = returnValue['token'] print( huepy.good('Downloaded identity certificate:' + returnValue['token'])) return True
# coding:utf-8 import os import sys import hashlib import socket import time import _thread import random import huepy print(huepy.good('Welcome use Flyvar')) # FlyVar Server Compment class Server(): def __init__(self, host='127.0.0.1', port=18012, maxlisten=30): self.host = host self.port = port self.maxlisten = maxlisten self.__connections = list() self.__client = list() self.__token = list() def Runing(self): try: os.mkdir('flying') except: pass self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
from challenge03 import xor_decrypt, read_data from huepy import good, info, bold if __name__ == '__main__': # One of the 60-character strings in the file # has been encrypted by single-character XOR. encrypted_data = read_data('4', out_multiline=True) decrypted_data = [] for line in encrypted_data: decrypted_data.append(xor_decrypt(line)) sorted_score = sorted(decrypted_data, key=lambda tup: tup[0])[0] print(info(f'input_hex: {sorted_score[3]}')) print(good(f'score: {sorted_score[1]}')) print(good(f'cipher key: {sorted_score[0]} ( {chr(sorted_score[0])} )')) print(bold(good(f'decrypted_string: {sorted_score[2].encode()}')))
from huepy import run, info, good, bad if __name__ == '__main__': # Write a function that takes two equal-length buffers # and produces their XOR combination. # If your function works properly, then when you feed it the string: string1_hex = "1c0111001f010100061a024b53535009181c" print(run(f'string1 hex: {string1_hex}')) string1_dec = hex2dec(string1_hex, True) print(run(f'string1 decoded: {string1_dec}')) # ... after hex decoding, and when XOR'd against: string2_hex = "686974207468652062756c6c277320657965" print(run(f'string2 hex: {string2_hex}')) string2_dec = hex2dec(string2_hex, True) print(run(f'string2 decoded: {string2_dec}')) # ... should produce: expected_result = "746865206b696420646f6e277420706c6179" xored_dec = xor_strings(string1_dec, string2_dec, bytes_out=True) print(info(f'xored_decoded: {xored_dec}')) xored_hex = hexlify(xored_dec).decode('utf-8') print(info(f'xored_hex: {xored_hex}')) print(info(f'expected_result: {xored_hex}')) if xored_hex == expected_result: print(good('result true')) else: print(bad('keep trying...'))
test_ciphertext = encryption_oracle.encrypt(prefix + known_bytes + bytes([i])) if test_ciphertext[:test_length] == real_ciphertext[:test_length]: return bytes([i]) return b'' if __name__ == '__main__': data = read_data('12') encryption_oracle = EncryptionOracleECB(data) print(run("Discovering block size...")) block_size = discover_block_size(encryption_oracle) print(good(f"Block size: {block_size} bytes")) if not detect_ecb_mode(encryption_oracle): print(bad("The cipher is NOT using ECB mode")) else: print(info("The cipher is using ECB mode")) decrypted_data = b'' data_length = len(encryption_oracle.encrypt(b'')) for i in range(data_length): next_byte = find_byte(encryption_oracle, block_size, decrypted_data) decrypted_data += next_byte # print(decrypted_data) print(run("Decrypting: " + "{:4.2f}".format(100 * (i + 1) / data_length) + "%"), end='\r') print(good("Decryption complete!"))
from huepy import good, info from utils import divide_in_blocks, read_data if __name__ == '__main__': """Detect AES in ECB mode""" encrypted_data_hex = read_data('8', out_multiline=True) scores = [] for encrypted_line_hex in encrypted_data_hex: encrypted_line_blocks = divide_in_blocks(encrypted_line_hex, 16) score = len(encrypted_line_blocks) - len(set(encrypted_line_blocks)) scores.append(score) max_score = max(scores) positions = [i for i, j in enumerate(scores) if j == max_score] # note that in fact only one score != 0 for i in range(len(positions)): ecb = divide_in_blocks(encrypted_data_hex[positions[i]], 16) print(info("Ciphertext encrypted with AES-ECB:")) for block_slice in ecb: print(block_slice) print(good(f"Line location: {positions[i]}")) print(good(f"Number of repeated blocks: {scores[positions[i]]}")) # the same 16 byte plaintext block will always produce the same 16 byte ciphertext
#!/usr/bin/env python3 # huepy muss vorher installiert werden. import huepy print(huepy.bold(huepy.red("red and bold"))) print(huepy.run("Starte...")) print(huepy.info("Info!!")) print(huepy.bad("Schlecht!")) print(huepy.good("Gut!")) input(huepy.que("Frage? ")) # mit Fortschritt: from tqdm import tqdm for x in tqdm(range(5000000), desc=huepy.run("Dinge")): pass
cipher_array[sorted_score[j][0]], string_hex)) return result_array def xor_decrypt(string_hex): xor_array = xor_cipher(string_hex) # cipher by every char xor_score = xor_cipher_score(xor_array) # score result = xor_result(xor_score, xor_array, string_hex) # order by score # debug results: # print('(key, score, string_decrypted)') # for j in range(0, 10): # print(result[j]) final_result = result[0] # first one with better score return final_result if __name__ == '__main__': # The hex encoded string has been XOR'd against a single character. # Find the key, decrypt the message. input_string_hex = read_data('3', out_multiline=False) # Crack XOR encryption final_result = xor_decrypt(input_string_hex) print(info(f'final result:')) print(info(f'key: { final_result[0] } ({ chr(final_result[0]) })')) print(info(f'score: { final_result[1] }')) print(bold(good(f'decrypted string: { final_result[2] }')))
print(info(f"Oracle: {lpurple('ECB')}")) else: iv = generate_aes_key() cipher_text = aes128_cbc_encrypt(plain_text_ext, iv, key) print(info(f"Oracle: {lblue('CBC')}")) return cipher_text if __name__ == '__main__': ''' This function detect if ECB of CBC mode is used The problem with ECB is that it is stateless and deterministic; the same 16 byte plaintext block will always produce the same 16 byte ciphertext. Due that, if we generate always the same data, the ecb mode will be always output the same ciphertext (except the random bytes added) ''' data = bytes([0]) * 200 cipher_text = encryption_oracle(data) blocks = divide_in_blocks(cipher_text, 16) num_repeated_blocks = len(blocks) - len(set(blocks)) if num_repeated_blocks: print(run(f"Number of repeated blocks: {red(num_repeated_blocks)}")) print(good(f"The cipher is using {lpurple('ECB')} mode")) else: print(run(f"Number of repeated blocks: {green(num_repeated_blocks)}")) print(good(f"The cipher is using {lblue('CBC')} mode"))
if len(argv) == 2: print(get_size_once_padded(argv[1], 16), end="") elif len(argv) == 4: unloaded = ELF(argv[1]) # :/ iv = b"0123456789012345" surprise = unloaded.get_section_by_name(".fini.") text = unloaded.get_section_by_name(".text") # computing .text section sha256 text_sum = sha256(text.data).hexdigest() print(good(".text sha256 sum : ") + text_sum) key = bytearray.fromhex(text_sum) binary_to_be_packed = pad(open(argv[2], "rb").read(), 16) encryptor = AES.new(key, AES.MODE_CBC, iv) # we are adding 16 bytes of metada, which are the place holder for the timestamp of the last run and the address of the .fini. section on disk. encrypted = (pack("<Q", 0) + pack("<Q", surprise.sh_offset) + encryptor.encrypt(binary_to_be_packed)) surprise.data = encrypted print(good("encrypted binary size : {}".format(len(encrypted)))) unloaded.save(argv[3])
def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', dest='url', metavar='URL', required=True, help='URL https://example.com') parser.add_argument( '--verify', action='store_true', default=False, help='Verify the SSL certificate. Default is set to False.') parser.add_argument('--description', action='store_true', help='Print header description') args = parser.parse_args() session = requests.Session() session.headers.update({ 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0', 'Cache-control': 'no-cache', 'Pragma': 'no-cache', 'Connection': 'close' }) # prepend http if missing args.url = 'http://' + args.url if not args.url.startswith( 'http') else args.url if not valid_url(args.url): parser.print_help() exit() try: response = session.get(url=args.url, verify=args.verify) except requests.exceptions.ConnectionError as e: print(bold(bad(f"{bold(red('connection error'))}: {e}"))) print(bold(bad(f'{args.url}'))) exit() except Exception: print(bold(bad(bold(red('connection error'))))) print(bold(bad(f'{args.url}'))) exit() headers = response.headers html = response.text soup = BeautifulSoup(html, "lxml") wappalyzer_json_url = "https://raw.githubusercontent.com/AliasIO/wappalyzer/master/src/technologies.json" check_headers = [ 'X-Content-Type-Options', 'X-Frame-Options', 'X-XSS-Protection', 'Strict-Transport-Security', 'Content-Security-Policy', 'Referrer-Policy', 'Feature-Policy' ] descriptions = {} descriptions['X-Content-Type-Options'] = que( 'X-Content-Type-Options stops a browser from trying to MIME-sniff the content type and forces it to stick with the declared content-type. The only valid value for this header is "X-Content-Type-Options: nosniff".' ) descriptions['X-Frame-Options'] = que( 'X-Frame-Options tells the browser whether you want to allow your site to be framed or not. By preventing a browser from framing your site you can defend against attacks like clickjacking.' ) descriptions['X-XSS-Protection'] = que( 'X-XSS-Protection sets the configuration for the XSS Auditor built into older browser. The recommended value was "X-XSS-Protection: 1; mode=block" but you should now look at Content Security Policy instead.' ) descriptions['Strict-Transport-Security'] = que( 'HTTP Strict Transport Security is an excellent feature to support on your site and strengthens your implementation of TLS by getting the User Agent to enforce the use of HTTPS.' ) descriptions['Content-Security-Policy'] = que( 'Content Security Policy is an effective measure to protect your site from XSS attacks. By whitelisting sources of approved content, you can prevent the browser from loading malicious assets. Analyse this policy in more detail. You can sign up for a free account on Report URI to collect reports about problems on your site.' ) descriptions['Referrer-Policy'] = que( 'Referrer-Policy Referrer Policy is a new header that allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites.' ) descriptions['Feature-Policy'] = que( 'Feature Policy is a new header that allows a site to control which features and APIs can be used in the browser.' ) cookie_checks = [ 'Expires', 'HttpOnly', 'Secure', 'Path=/', ] print(info(f"{bold('Request URL')}: {args.url}")) print(info(f"{bold('Response status code')}: {response.status_code}")) print(info(bold('Request headers:'))) print(json.dumps(dict(session.headers), indent=2, sort_keys=True)) print(info(bold('Response headers:'))) print(json.dumps(dict(headers), indent=2, sort_keys=True)) print(f"\n{run(bold('Checking security headers...'))}") for check_head in check_headers: if check_head.lower() in headers: print(good(f'{check_head} found')) else: print(bad(f'{check_head} not found')) if args.description: if check_head in descriptions.keys(): print(descriptions[check_head]) print(f"\n{run(bold('Checking cookies...'))}") if 'set-cookie' in headers: cookies = headers['Set-Cookie'].split(',') for cookie in cookies: print(f"{bold('cookie: ')} {cookie}") for cookie_check in cookie_checks: if cookie_check.lower() in cookie.lower(): print(good(f'{cookie_check} found')) else: print(bad(f'{cookie_check} not found')) else: print(info('not found')) print(f"\n{run(bold('Checking Wappalyzer Regular Expressions...'))}") # Prepare wappalyzer data wappalyzer_json_file = requests.get(wappalyzer_json_url) if wappalyzer_json_file.ok: try: wappalyzer_json = json.loads(wappalyzer_json_file.text) except json.decoder.JSONDecodeError as e: print(bold(bad(f"{bold(red('JSONDecodeError'))}: {e}"))) exit() else: print( bold( bad(f"{bold(red(f'Unable to get wappalyzer json file {wappalyzer_json_url}'))}" ))) exit() wappalyzer_categories = wappalyzer_json['categories'] saved_apps = {} for k, v in wappalyzer_categories.items(): name = wappalyzer_categories[k]['name'] saved_apps[name] = set() wappalyzer_tech = wappalyzer_json['technologies'] wappalyzer_names = {} for app_name, details in wappalyzer_tech.items(): wappalyzer_names[app_name] = set() if 'cats' in details.keys(): for ca in details['cats']: wappalyzer_names[app_name].add(ca) # Parse meta data metas = [] for meta in soup.findAll('meta'): meta_object = list(meta.attrs.keys()) + list(meta.attrs.values()) metas.append(meta_object) for app_name, details in wappalyzer_tech.items(): found = False try: # Check meta if 'meta' in details.keys(): for k, v in details['meta'].items(): for meta in metas: if k in meta and re.search(v, ' '.join(meta)): for cat in details['cats']: name = wappalyzer_categories[str(cat)]['name'] saved_apps[name].add(app_name) found = True # Check headers if 'headers' in details.keys(): for k, header in details['headers'].items(): if k in headers and re.search(headers[k], header): for cat in details['cats']: name = wappalyzer_categories[str(cat)]['name'] saved_apps[name].add(app_name) found = True # Check html and script search_in_html = [] if 'html' in details.keys(): if isinstance(details['html'], list): search_in_html += details['html'] if isinstance(details['html'], str): search_in_html.append(details['html']) if 'script' in details.keys(): if isinstance(details['script'], list): search_in_html += details['script'] if isinstance(details['script'], str): search_in_html.append(details['script']) for regex in search_in_html: if re.search(regex, html): for cat in details['cats']: name = wappalyzer_categories[str(cat)]['name'] saved_apps[name].add(app_name) found = True if found and 'implies' in details.keys(): if isinstance(details['implies'], list): techs = details['implies'] elif isinstance(details['implies'], str): techs = [details['implies']] else: techs = [] for tech in techs: subcats = wappalyzer_names[tech] for subcat in subcats: subcat_category = wappalyzer_categories[str( subcat)]['name'] saved_apps[subcat_category].add(tech) except re.error: # print(warn(f'regex error: {regex}')) pass wappalyzer_found = False for category, app_names in saved_apps.items(): if app_names: wappalyzer_found = True output = info(f"{category}: {', '.join(map(str, app_names))}") print(output) if not wappalyzer_found: print(info('not found'))
# stub = (c_char * len(stub)).from_buffer(bytearray(stub)).raw # e.get_section_by_name(".text").data = stub new_section.data = shellcode new_section.sh_name = 1 # choose a random name # right after the last sh there is the sht table so it offset will be the addr of the new section new_section.sh_offset = e.Elf64_Ehdr.e_shoff # nice if it would be filled automatically by save new_section.sh_size = len(new_section.data) new_section.sh_addralign = 16 new_section.sh_type = 0x1 # PROGBITS # adding our sections in the Shdt e.add_section(new_section) # need to extend the last segment to englobe our new section segment = e.Elf64_Phdr[5] segment.p_filesz = new_section.sh_offset + new_section.sh_size - segment.p_offset segment.p_memsz = new_section.sh_offset + new_section.sh_size - segment.p_offset segment.p_flags = 7 # RWX # modifying our entrypoint to point to the shellcode e.Elf64_Ehdr.e_entry = segment.p_vaddr - segment.p_offset + new_section.sh_offset print(good("Entry at {}".format(hex(e.Elf64_Ehdr.e_entry)))) e.save(argv[2]) # excepted behavior: # - return 14 (echo $?)
for index, state in enumerate(states): if index == 0: e = aes128_RoundBlock(xor_states(state, iv_matrix), key) else: e = aes128_RoundBlock(xor_states(state, pre_ciphertext_state), key) pre_ciphertext_state = e cipher_text += matrix_to_bytes(e) return cipher_text if __name__ == '__main__': # Implement CBC mode key = b'YELLOW SUBMARINE' iv = b'\x00' * 16 encrypted_data_base64 = read_data('10') encrypted_data = a2b_base64(encrypted_data_base64) plain_text = aes128_cbc_decrypt(encrypted_data, iv, key) cipher_text = aes128_cbc_encrypt(plain_text, iv, key) if cipher_text == encrypted_data: print(good('AES128 CBC MODE WORKS CORRECTLY')) else: print(bad('ERROR!')) print(plain_text.decode())
# coding:utf-8 from flask import * import os import hashlib import time import _thread import random import huepy import traceback print(huepy.good('Welcome to the flyvar command tool, enter "help" for help')) while True: cmd = input('anything:') if cmd == "help": print('') print(huepy.info('Existing instructions:')) print('') print(huepy.info('createdatabase:Create Database')) print('') print(huepy.info('createdatabase:Create Database')) print('') elif cmd == "createdatabase": cmd = input('DatabaseName:') if cmd.isalpha() and cmd.islower(): if not os.path.exists("./" + cmd + '.fvdata'): cmd1 = input('Password:'******'utf-8')) with open('./' + cmd + '.fvdata', 'wb+') as fh: fh.write(
def good(text): print(huepy.good(text))
from utils import xor_strings, dec2hex from huepy import good, bad def encrypt_repeating_key_xor(key, input_string): encrypted = "" for i in range(int(len(input_string) / len(key) + 1)): substring = input_string[i * len(key):(i + 1) * len(key)] encrypted += xor_strings(substring, key) return dec2hex(encrypted) if __name__ == '__main__': # Implement repeating-key XOR input_string = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" key = "ICE" # input_string = input("Enter string: ") # key = input("Enter key: ") encrypted_string = encrypt_repeating_key_xor(key, input_string) expected_result = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f' if encrypted_string == expected_result: print(good('Encryption correct')) else: print(bad('Encryption incorrect'))
class KeyProcessor(PacketProcessor): """Key sniffer processor Sniffs a pairing procedure to get all link information, including the AES key """ def __init__(self): PacketProcessor.__init__(self) self.wait_pair_cmd = True self.key_index = 0 self.key_words = [None] * 0x25 self.link_config = LinkConfig() self.success = False def process(self, data): print(hue.info("Processing packet ...")) # Check if the 802.15.4 packet is valid if makeFCS(data[:-2]) != data[-2:]: print(hue.bad("Invalid packet")) return # Parse 802.15.4 packet and extract RF4CE payload packet = Dot15d4FCS(data) if packet.fcf_frametype == 2: # ACK return # Read source, dest, do not use key if packet.fcf_srcaddrmode == 3: source = Rf4ceNode(packet.src_addr, None) destination = Rf4ceNode(packet.dest_addr, None) else: source = Rf4ceNode(None, packet.src_addr) destination = Rf4ceNode(None, packet.dest_addr) key = None rf4ce_payload = bytes(packet[3].fields["load"]) frame = Rf4ceFrame() try: frame.parse_from_string(rf4ce_payload, source, destination, key) except Rf4ceException, e: print(hue.bad("Cannot parse RF4CE frame: {}".format(e))) return # Start of a key transmission can be detected with # the pairing response command (0x04) # Short addresses for source and destination are also # provided by this command if self.wait_pair_cmd: if frame.frame_type == Rf4ceConstants.FRAME_TYPE_COMMAND: if frame.command == 0x04: print(hue.good("Key transmission started !")) short_src, short_dest = self.parse_pairing_response( frame.payload) self.link_config.dest_panid = packet.src_panid self.link_config.source = Rf4ceNode( packet.dest_addr, short_src) self.link_config.destination = Rf4ceNode( packet.src_addr, short_dest) self.wait_pair_cmd = False # Here, we are now expecting key seed command frames (0x06) else: if frame.frame_type != Rf4ceConstants.FRAME_TYPE_COMMAND: print( hue.bad( "Received unexpected frame type: {}".format(frame))) return if frame.command != 0x06: print(hue.bad("Received unexpected command: {}".format(frame))) return if frame.payload[0] == self.key_index - 1: self.key_index -= 1 print( hue.info("Key word {} has been sent again".format( self.key_index))) if frame.payload[0] != self.key_index: print( hue.bad("Missed key word {} ! Aborting.".format( self.key_index))) self.stop() return print(hue.good("Received key word {}".format(self.key_index))) self.key_words[self.key_index] = frame.payload[1:] if self.key_index == 0x24: print(hue.good("All key words have been received")) self.link_config.key = binascii.hexlify( self.compute_key(self.key_words)) self.link_config.frame_counter = frame.frame_counter self.success = True self.stop() else: self.key_index += 1
d = matrix_to_bytes(aes128_InvRoundBlock(state, key)) plain_text += d return plain_text def aes128_ecb_encrypt(plain_text, key): states = string_to_matrix_states(plain_text) cipher_text = b'' for state in states: d = matrix_to_bytes(aes128_RoundBlock(state, key)) cipher_text += d return cipher_text if __name__ == '__main__': key = b'YELLOW SUBMARINE' encrypted_data_base64 = read_data('7') encrypted_data = a2b_base64(encrypted_data_base64) plain_text = aes128_ecb_decrypt(encrypted_data, key) cipher_text = aes128_ecb_encrypt(plain_text, key) if cipher_text == encrypted_data: print(good('AES128 ECB MODE WORKS CORRECTLY')) else: print(bad('ERROR!')) print(plain_text.decode())