def portionBucket(): cryptorand = SystemRandom() print("Portioning images from bucket..") if len(os.listdir("PLACE_IMAGES_HERE/normal/")) > 0: print("Portioning normal images..") transferlist = list(Path('.').glob("PLACE_IMAGES_HERE/normal/*.jpg")) cryptorand.shuffle(transferlist) portionlimit = transferlist.__len__() / 3 index = 0 for s in transferlist: index += 1 if index < portionlimit: os.rename(s, "internal/test_set/normal/" + str(s)[25:]) else: os.rename(s, "internal/training_set/normal/" + str(s)[25:]) else: print("No normal images found.") if len(os.listdir("PLACE_IMAGES_HERE/abnormal/")) > 0: print("Portioning abnormal images..") transferlist = list(Path('.').glob("PLACE_IMAGES_HERE/abnormal/*.jpg")) cryptorand.shuffle(transferlist) portionlimit = transferlist.__len__() / 3 index = 0 for s in transferlist: index += 1 if index < portionlimit: os.rename(s, "internal/test_set/abnormal/" + str(s)[27:]) else: os.rename(s, "internal/training_set/abnormal/" + str(s)[27:]) else: print("No abnormal images found.") print("Images portioned.")
def generate_groups(self): """ Generates the groups based on a randomization algorithm. :return: the generated groups: a list of lists (names) """ if not self.names: raise AttributeError("Could not find names list. Try re-initializing Engine with valid filepath.") groups = [] cryptogen = SystemRandom() cryptogen.shuffle(self.names) current_group = [] for name in self.names: current_group.append(name) is_last_name = self.names.index(name) == len(self.names) - 1 is_group_full = len(current_group) == self.group_size if is_group_full or is_last_name: groups.append(current_group) current_group = [] logging.info("Created {} groups with max size {}.".format(len(groups), self.group_size)) return groups
def generate_groups(self): """ Generates the groups based on a randomization algorithm. :return: the generated groups: a list of lists (names) """ if not self.names: raise AttributeError( "Could not find names list. Try re-initializing Engine with valid filepath." ) groups = [] cryptogen = SystemRandom() cryptogen.shuffle(self.names) current_group = [] for name in self.names: current_group.append(name) is_last_name = self.names.index(name) == len(self.names) - 1 is_group_full = len(current_group) == self.group_size if is_group_full or is_last_name: groups.append(current_group) current_group = [] logging.info("Created {} groups with max size {}.".format( len(groups), self.group_size)) return groups
def main(args): r = SystemRandom() try: try: _min = int(args[1]) _max = int(args[2]) except: _min = 0 _max = int(args[1]) except: _min = 0 _max = 10 try: if args[0] == 'simple': l = list(string.letters + string.digits) r.shuffle(l) return ''.join(l[0:_max]) if args[0] == 'strong': l = list(string.letters + string.digits + string.punctuation) r.shuffle(l) return ''.join(l[0:_max]) if args[0] == 'integer': return r.randint(_min, _max) return r.uniform(_min, _max) except: return r.random()
def tcp_scan(ips, ports, randomize=True): loop = asyncio.get_event_loop() if randomize: rdev = SystemRandom() ips = rdev.shuffle(ips) ports = rdev.shuffle(ports) tcp_Scanner_run(tcp_scanner(ip, port) for port in ports for ip in ips)
def scan(ips, ports, randomize=False): """Scan the ports""" loop = asyncio.get_event_loop() if randomize: rdev = SystemRandom() ips = rdev.shuffle(ips) ports = rdev.shuffle(ports) # let's pass list of task, not only one run([scanner(ip, port) for port in ports for ip in ips])
def __init__(self, mode='test', limiter=0, shuffle_en=False): name = 'waymo' self.type = 'lidar' db.__init__(self, name, mode) self._train_scenes = [] self._val_scenes = [] self._test_scenes = [] if (mode == 'test'): self._tod_filter_list = cfg.TEST.TOD_FILTER_LIST else: self._tod_filter_list = cfg.TRAIN.TOD_FILTER_LIST self._uncertainty_sort_type = cfg.UC.SORT_TYPE self._draw_width = int((cfg.LIDAR.X_RANGE[1] - cfg.LIDAR.X_RANGE[0]) * (1 / cfg.LIDAR.VOXEL_LEN)) self._draw_height = int((cfg.LIDAR.Y_RANGE[1] - cfg.LIDAR.Y_RANGE[0]) * (1 / cfg.LIDAR.VOXEL_LEN)) self._num_slices = cfg.LIDAR.NUM_SLICES self._bev_slice_locations = [1, 2, 3, 4, 5, 7] self._filetype = 'npy' self._imtype = 'PNG' self._scene_sel = True #For now one large cache file is OK, but ideally just take subset of actually needed data and cache that. No need to load nusc every time. self._classes = ( 'dontcare', # always index 0 'vehicle.car') # 'human.pedestrian', #'vehicle.bicycle') self.config = {'cleanup': True, 'matlab_eval': False, 'rpn_file': None} self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) self._train_index = os.listdir( os.path.join(self._devkit_path, 'train', 'point_clouds')) self._val_index = os.listdir( os.path.join(self._devkit_path, 'val', 'point_clouds')) self._val_index.sort(key=natural_keys) rand = SystemRandom() if (shuffle_en): print('shuffling pc indices') rand.shuffle(self._train_index) rand.shuffle(self._val_index) if (limiter != 0): if (limiter < len(self._val_index)): self._val_index = self._val_index[:limiter] if (limiter < len(self._train_index)): self._train_index = self._train_index[:limiter] if (limiter < len(self._test_index)): self._test_index = self._test_index[:limiter] #if(18000 < len(self._val_index)): # self._val_index = self._val_index[:18000] assert os.path.exists( self._devkit_path), 'waymo dataset path does not exist: {}'.format( self._devkit_path)
def bogo_solve(constraints): names = get_names(constraints) rng = SystemRandom() while verify(names, constraints) != []: rng.shuffle(names) s = "" for n in names: s += n + " " print "Ordering: {}".format(s)
def fillBucket(): cryptorand = SystemRandom() print("Putting images into bucket..") if len(os.listdir("internal/training_set/normal")) > 0: print("Taking normal images..") transferlist = list( Path('.').glob("internal/training_set/normal/*.jpg")) cryptorand.shuffle(transferlist) for s in transferlist: os.rename(s, "PLACE_IMAGES_HERE/normal/" + str(s)[29:]) transferlist = list(Path('.').glob("internal/test_set/normal/*.jpg")) cryptorand.shuffle(transferlist) for s in transferlist: os.rename(s, "PLACE_IMAGES_HERE/normal/" + str(s)[25:]) else: print("No normal images found.") if len(os.listdir("internal/training_set/abnormal")) > 0: print("Taking abnormal images..") transferlist = list( Path('.').glob("internal/training_set/abnormal/*.jpg")) cryptorand.shuffle(transferlist) for s in transferlist: os.rename(s, "PLACE_IMAGES_HERE/abnormal/" + str(s)[31:]) transferlist = list(Path('.').glob("internal/test_set/abnormal/*.jpg")) cryptorand.shuffle(transferlist) for s in transferlist: os.rename(s, "PLACE_IMAGES_HERE/abnormal/" + str(s)[27:]) else: print("No abnormal images found.") print("Images moved to bucket.")
def init_captcha(): dice = SystemRandom() normalset, oddballset = dice.sample(current_app.captcha_data, 2) normals = dice.sample(normalset, NORMALS) oddballs = dice.sample(oddballset - normalset, ODDBALLS) united = normals + oddballs dice.shuffle(united) challenge = ' '.join(united) expiry = datetime.today() + AUTHENTICATION_TIME session['captcha-answer'] = map(lambda s: s.lower(), oddballs) session['captcha-expires'] = expiry if 'captcha-quarantine' in session: del session['captcha-quarantine'] session.modified = True return {'captcha_expires': str(expiry), 'captcha_challenge': challenge}
def generate_wordlist(num_words, num_letters, num_digits, num_symbols): rng = SystemRandom() wordlist_set = set() for _ in range(num_words): letters = ''.join( rng.choice(string.ascii_letters) for _ in range(num_letters)) digits = ''.join(rng.choice(string.digits) for _ in range(num_digits)) symbols = ''.join( rng.choice(string.punctuation) for _ in range(num_symbols)) word = letters + digits + symbols word_l = list(word) rng.shuffle(word_l) wordlist_set.add(''.join(word_l)) return wordlist_set
def generate_sequence(): cryptorand = SystemRandom() sequence = [] for i in range(22): flip = random.randint(1, 2) if flip == 1: sequence.append("0") else: sequence.append("O") random.seed() cryptorand.shuffle(sequence) return "O" + "".join(sequence)
def start(format): random = SystemRandom() randomCharacterList = formatDict.get(format)[ 1] # Get encoding alphabet based on user input random.shuffle( randomCharacterList) # Randomize the alphabet order for extra random keyListLength = len(randomCharacterList) keyList = [] for _ in range( formatDict.get(format) [0]): # Add random characters from the encoding alphabet to a list i = random.randint(1, keyListLength) n = randomCharacterList[i - 1] keyList.append(n) privateKey = "".join(keyList) # Join the character list into a key string return privateKey
def __init__(self, mode='test', limiter=0): name = 'nuscenes' db.__init__(self, name) self._train_scenes = [] self._val_scenes = [] self._test_scenes = [] self._train_index = [] self._val_index = [] self._test_index = [] self._devkit_path = self._get_default_path() self._mode = mode self._nusc = None self._scene_sel = True #For now one large cache file is OK, but ideally just take subset of actually needed data and cache that. No need to load nusc every time. self._classes = ( 'dontcare', # always index 0 'vehicle.car', 'human.pedestrian', 'vehicle.bicycle') self.config = {'cleanup': True, 'matlab_eval': False, 'rpn_file': None} self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) self._val_scenes = create_splits_scenes()['val'] self._train_scenes = create_splits_scenes()['train'] self._test_scenes = create_splits_scenes()['test'] #TODO: create custom scene list #print(self._train_scenes) for rec in self.nusc.sample_data: if (rec['channel'] == 'CAM_FRONT' and rec['is_key_frame'] is True): rec_tmp = deepcopy(rec) #Reverse lookup, getting the overall sample from the picture sample token, to get the scene information. scene_name = self.nusc.get( 'scene', self.nusc.get('sample', rec['sample_token'])['scene_token'])['name'] desc = self.nusc.get( 'scene', self.nusc.get('sample', rec['sample_token']) ['scene_token'])['description'].lower() if (self._scene_sel and 'night' not in desc and 'rain' not in desc and 'cones' not in desc): sample = self.nusc.get('sample', rec['sample_token']) rec_tmp['anns'] = sample['anns'] rec_tmp['lidar_token'] = sample['data']['LIDAR_TOP'] if (scene_name in self._train_scenes): self._train_index.append(rec_tmp) elif (scene_name in self._val_scenes): self._val_index.append(rec_tmp) elif (scene_name in self._train_scenes): self._test_index.append(rec_tmp) rand = SystemRandom() #Get global image info if (mode == 'train'): img_index = self._train_index rand.shuffle(self._val_index) elif (mode == 'val'): img_index = self._val_index elif (mode == 'test'): img_index = self._test_index self._imwidth = img_index[0]['width'] self._imheight = img_index[0]['height'] self._imtype = img_index[0]['fileformat'] rand = SystemRandom() rand.shuffle(img_index) if (limiter != 0): img_index = img_index[:limiter] if (mode == 'train'): self._train_index = img_index elif (mode == 'val'): self._val_index = img_index elif (mode == 'test'): self._test_index = img_index assert os.path.exists( self._devkit_path ), 'nuscenes dataset path does not exist: {}'.format(self._devkit_path)
pseudo_id = namedtuple('pseudo_id', ['pseudonym', 'code', 'cryptonym']) voter_list = voters_in_text.strip().splitlines() word_list = unique_words.strip().splitlines() random = SystemRandom() random_words = random.sample(word_list, len(voter_list)) random_keys = random.sample(code_range, len(voter_list)) print("There are %d voters in upcoming election:\n" % len(voter_list)) for voter in voter_list: print(voter) random.shuffle(voter_list) print() print("Distributing pseudonyms...\n") pseudo = [] for i in range(len(voter_list)): current = pseudo_id(random_words[i], str(random_keys[i]), random_words[i] + str(random_keys[i])) pseudo.append(current) i = -1 try:
def shuffle(elements): cryptorand = SystemRandom() cryptorand.shuffle(elements)
def __init__(self, nboxes, nguess): self.nboxes = nboxes self.nguess = nguess rnd = SystemRandom() self.boxes = list(range(1, nboxes + 1)) rnd.shuffle(self.boxes)
def __init__(self, mode='test',limiter=0, shuffle_en=True): name = 'kitti' db.__init__(self, name, mode) self._devkit_path = self._get_default_path() self._data_path = self._devkit_path self._mode = mode self._uncertainty_sort_type = cfg.UC.SORT_TYPE self._draw_width = int((cfg.LIDAR.X_RANGE[1] - cfg.LIDAR.X_RANGE[0])*(1/cfg.LIDAR.VOXEL_LEN)) self._draw_height = int((cfg.LIDAR.Y_RANGE[1] - cfg.LIDAR.Y_RANGE[0])*(1/cfg.LIDAR.VOXEL_LEN)) self._num_slices = cfg.LIDAR.NUM_SLICES self._frame_sub_dir = 'velodyne' self._train_dir = os.path.join(self._data_path, 'training', self._frame_sub_dir) self._val_dir = os.path.join(self._data_path, 'training', self._frame_sub_dir) self._test_dir = os.path.join(self._data_path, 'testing', self._frame_sub_dir) self._split_dir = os.path.join(self._data_path, 'splits') self._test_index = open(self._split_dir+'/test.txt').read().splitlines() self._train_index = open(self._split_dir+'/train.txt').read().splitlines() self._val_index = open(self._split_dir+'/val.txt').read().splitlines() self._filetype = 'bin' self._imtype = 'PNG' self.type = 'lidar' self._bev_slice_locations = [1,2,3,4,5,7] self._mode = mode #Backwards compatibility self._train_sub_folder = 'training' self._val_sub_folder = 'training' self._test_sub_folder = 'testing' self._classes = ( 'dontcare', # always index 0 #'Pedestrian', #'Cyclist', 'Car') self.config = { 'cleanup': True, 'matlab_eval': False, 'rpn_file': None } self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) #self._train_index = sorted([d for d in os.listdir(self._train_dir) if d.endswith('.bin')]) #self._val_index = sorted([d for d in os.listdir(self._val_dir) if d.endswith('.bin')]) #self._test_index = sorted([d for d in os.listdir(self._test_dir) if d.endswith('.bin')]) #Limiter if(limiter != 0): if(limiter < len(self._val_index)): self._val_index = self._val_index[:limiter] if(limiter < len(self._train_index)): self._train_index = self._train_index[:limiter] if(limiter < len(self._test_index)): self._test_index = self._test_index[:limiter] rand = SystemRandom() if(shuffle_en): print('shuffling frame indices') rand.shuffle(self._val_index) rand.shuffle(self._train_index) rand.shuffle(self._test_index) assert os.path.exists(self._devkit_path), \ 'Kitti dataset path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path)
def __init__(self, mode='test', limiter=0, shuffle_en=True): name = 'cadc' db.__init__(self, name, mode) self._devkit_path = self._get_default_path() self._data_path = self._devkit_path self._mode = mode self._uncertainty_sort_type = cfg.UC.SORT_TYPE self._frame_sub_dir = 'image_00' if (mode == 'test'): self._tod_filter_list = cfg.TEST.CADC_FILTER_LIST else: self._tod_filter_list = cfg.TRAIN.CADC_FILTER_LIST scene_desc_filename = os.path.join(self._data_path, 'cadc_scene_description.csv') self._load_scene_meta(scene_desc_filename) self._train_dir = os.path.join(self._data_path, 'train', self._frame_sub_dir) self._val_dir = os.path.join(self._data_path, 'val', self._frame_sub_dir) #self._test_dir = os.path.join(self._data_path, 'testing', self._frame_sub_dir) crop_top = 150 crop_bottom = 250 self._imwidth = 1280 self._imheight = 1024 - crop_top - crop_bottom self._imtype = 'png' self._filetype = 'png' self.type = 'image' self._mode = mode #Backwards compatibility #self._train_sub_folder = 'training' #self._val_sub_folder = 'evaluation' #self._test_sub_folder = 'testing' self._classes = ( 'dontcare', # always index 0 #'Pedestrian', #'Cyclist', 'Car') self.config = {'cleanup': True, 'matlab_eval': False, 'rpn_file': None} self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) self._train_index = sorted( [d for d in os.listdir(self._train_dir) if d.endswith('.png')]) self._val_index = sorted( [d for d in os.listdir(self._val_dir) if d.endswith('.png')]) #self._test_index = sorted([d for d in os.listdir(self._test_dir) if d.endswith('.png')]) #Limiter if (limiter != 0): if (limiter < len(self._val_index)): self._val_index = self._val_index[:limiter] if (limiter < len(self._train_index)): self._train_index = self._train_index[:limiter] #if(limiter < len(self._test_index)): # self._test_index = self._test_index[:limiter] rand = SystemRandom() if (shuffle_en): print('shuffling image indices') rand.shuffle(self._val_index) rand.shuffle(self._train_index) #rand.shuffle(self._test_index) assert os.path.exists(self._devkit_path), \ 'cadc dataset path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path)
#!/usr/bin/env python3 from string import ascii_lowercase from itertools import product from random import SystemRandom from math import ceil, log from secretstuff import FLAG random = SystemRandom() ALPHABET = ascii_lowercase + "_" assert all(char in ALPHABET for char in FLAG) bigrams = [''.join(bigram) for bigram in product(ALPHABET, repeat=2)] random.shuffle(bigrams) S_box = {} for i in range(len(ALPHABET)): for j in range(len(ALPHABET)): S_box[ALPHABET[i]+ALPHABET[j]] = bigrams[i*len(ALPHABET) + j] assert len(set(S_box.keys())) == 27*27 def encrypt(message): if len(message) % 2: message += "_" message = list(message) rounds = int(2 * ceil(log(len(message), 2))) # The most secure amount of rounds for round in range(rounds): # Encrypt
from random import SystemRandom random = SystemRandom() lista = [] i,n = 0,0 qtd = int(input('Informe a quantidade de alunos na sala : ')) while i < qtd: a = str(input('Digite o nome do {:2}° aluno : '.format(i+1))) lista.append(a) i+=1 random.shuffle(lista) print('\nA lista sorteada foi :') while n < qtd: print('{:2}° aluno escolhido : {}'.format(n+1,lista[n])) n+=1
def __init__(self, mode='test', limiter=0, shuffle_en=True): name = 'cadc' db.__init__(self, name, mode) self._devkit_path = self._get_default_path() self._data_path = self._devkit_path self._mode = mode if (mode == 'test'): self._tod_filter_list = cfg.TEST.CADC_FILTER_LIST else: self._tod_filter_list = cfg.TRAIN.CADC_FILTER_LIST scene_desc_filename = os.path.join(self._data_path, 'cadc_scene_description.csv') self._load_scene_meta(scene_desc_filename) self._uncertainty_sort_type = cfg.UC.SORT_TYPE self._draw_width = int((cfg.LIDAR.X_RANGE[1] - cfg.LIDAR.X_RANGE[0]) * (1 / cfg.LIDAR.VOXEL_LEN)) self._draw_height = int((cfg.LIDAR.Y_RANGE[1] - cfg.LIDAR.Y_RANGE[0]) * (1 / cfg.LIDAR.VOXEL_LEN)) self._num_slices = cfg.LIDAR.NUM_SLICES self._frame_sub_dir = 'point_clouds' self._annotation_sub_dir = 'annotation_00' self._calib_sub_dir = 'calib' self._train_dir = os.path.join(self._data_path, 'train', self._frame_sub_dir) self._val_dir = os.path.join(self._data_path, 'val', self._frame_sub_dir) #self._test_dir = os.path.join(self._data_path, 'testing', self._frame_sub_dir) self._filetype = 'bin' self._imtype = 'PNG' self.type = 'lidar' self._bev_slice_locations = [1, 2, 3, 4, 5, 7] self._mode = mode #Backwards compatibility #self._train_sub_folder = 'training' #self._val_sub_folder = 'evaluation' #self._test_sub_folder = 'testing' self._classes = ( 'dontcare', # always index 0 #'Pedestrian', #'Cyclist', 'Car') self.config = {'cleanup': True, 'matlab_eval': False, 'rpn_file': None} self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) self._train_index = sorted( [d for d in os.listdir(self._train_dir) if d.endswith('.bin')]) self._val_index = sorted( [d for d in os.listdir(self._val_dir) if d.endswith('.bin')]) #self._test_index = sorted([d for d in os.listdir(self._test_dir) if d.endswith('.bin')]) #Limiter if (limiter != 0): if (limiter < len(self._val_index)): self._val_index = self._val_index[:limiter] if (limiter < len(self._train_index)): self._train_index = self._train_index[:limiter] #if(limiter < len(self._test_index)): # self._test_index = self._test_index[:limiter] rand = SystemRandom() if (shuffle_en): print('shuffling frame indices') rand.shuffle(self._val_index) rand.shuffle(self._train_index) #rand.shuffle(self._test_index) assert os.path.exists(self._devkit_path), \ 'cadc dataset path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path)
def __init__(self, mode='test', limiter=0, shuffle_en=True): name = 'kitti' db.__init__(self, name, mode) self._devkit_path = self._get_default_path() self._data_path = self._devkit_path self._mode = mode self._uncertainty_sort_type = cfg.UC.SORT_TYPE self._frame_sub_dir = 'image_2' self._train_dir = os.path.join(self._data_path, 'training', self._frame_sub_dir) self._val_dir = os.path.join(self._data_path, 'training', self._frame_sub_dir) self._test_dir = os.path.join(self._data_path, 'testing', self._frame_sub_dir) self._split_dir = os.path.join(self._data_path, 'splits') self._imwidth = 1242 self._imheight = 375 self._imtype = 'png' self._filetype = 'png' self.type = 'image' self._mode = mode #Backwards compatibility self._train_sub_folder = 'training' self._val_sub_folder = 'training' self._test_sub_folder = 'testing' self._classes = ( 'dontcare', # always index 0 #'Pedestrian', #'Cyclist', 'Car') self.config = {'cleanup': True, 'matlab_eval': False, 'rpn_file': None} self._class_to_ind = dict( list(zip(self.classes, list(range(self.num_classes))))) self._test_index = open(self._split_dir + '/test.txt').read().splitlines() self._train_index = open(self._split_dir + '/train.txt').read().splitlines() self._val_index = open(self._split_dir + '/val.txt').read().splitlines() #self._train_index = self._train_index + self._val_index[250:] #self._val_index = self._val_index[:250] #self._train_index = sorted([d for d in os.listdir(self._train_dir) if d.endswith('.png')]) #self._val_index = sorted([d for d in os.listdir(self._val_dir) if d.endswith('.png')]) #self._test_index = sorted([d for d in os.listdir(self._test_dir) if d.endswith('.png')]) #Limiter if (limiter != 0): if (limiter < len(self._val_index)): self._val_index = self._val_index[:limiter] if (limiter < len(self._train_index)): self._train_index = self._train_index[:limiter] if (limiter < len(self._test_index)): self._test_index = self._test_index[:limiter] rand = SystemRandom() if (shuffle_en): print('shuffling image indices') rand.shuffle(self._val_index) rand.shuffle(self._train_index) rand.shuffle(self._test_index) assert os.path.exists(self._devkit_path), \ 'Kitti dataset path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path)
class Encryptor(object): def __init__(self, characters=None, backlog=-1): self.random = SystemRandom() if characters is None: unicode_chars = [chr(i) for i in range(1, 1028)] self.characters = [c for c in unicode_chars] self.characters.remove('\r') self.characters.remove('\f') self.random.shuffle(self.characters) self.rev_ord = {} self.ord = {} self.range = len(self.characters) self.make_key(self.characters) self.mix = backlog def load_key_file(self, filepath='key'): with open(filepath, 'r') as f: key_data = f.read() self.characters = [c for c in key_data] self.make_key(self.characters) return self def save_key_file(self, filepath='key'): with open(filepath, 'w') as f: f.write(''.join(self.characters)) return self def make_key(self, characters): if characters is not self.characters: self.characters = characters self.rev_ord = {} self.ord = {} for i, char in enumerate(self.characters): self.rev_ord[i + 1] = char for key, value in self.rev_ord.items(): self.ord[value] = key self.range = len(self.characters) return self def increment(self, start, amount): rng = (1, self.range) remainder = amount % rng[1] amount = remainder # Number is equally divisible and we can use the starting number if amount >= rng[1] and remainder == 0: return start # Amount is more than the range and there is a remainder. if amount >= rng[1] and remainder > 0: return start + remainder increase = start + amount if increase <= rng[1]: return increase if increase > rng[1]: return increase % rng[1] def decrement(self, start, amount): rng = (1, self.range) remainder = amount % rng[1] amount = remainder if amount >= rng[1] and remainder == 0: return start if amount >= rng[1] and remainder > 0: return rng[1] - ((amount - start) % rng[1]) if amount < rng[1] and start - amount < rng[0]: return rng[1] - (amount - start) if amount < rng[1] and start - amount >= rng[0]: return start - amount def encrypt(self, string): if not string: # raise ValueError("String cannot be empty.") return string first_letter_ord = self.ord[string[0]] output = "" mix = 0 for i, c in enumerate(string): increase = sum([self.ord[x] for x in string[:i][self.mix:]]) c_ord = self.increment(self.ord[c], increase + mix) mix += increase if i == 0: out = c else: _ = self.increment(first_letter_ord, c_ord) out = self.rev_ord[_] output += out first_letter_ord = self.ord[c] first_letter_number = self.increment( self.ord[string[0]], sum([self.ord[x] for x in output[self.mix:]])) output = self.rev_ord[first_letter_number] + output[1:] return output def decrypt(self, string): if not string: # raise ValueError("String cannot be empty.") return string first_letter_ord = self.ord[string[0]] if not first_letter_ord: raise ValueError("Your message is invalid.") output = "" # Set string's first letter to the correct un-encoded letter. first_letter_number = self.decrement( first_letter_ord, sum([self.ord[x] for x in string[self.mix:]])) first_letter = self.rev_ord[first_letter_number] string = first_letter + string[1:] mix = 0 for i, c in enumerate(string): increase = sum([self.ord[x] for x in output[:i][self.mix:]]) c_ord = self.decrement(self.ord[c], increase + mix) mix += increase if i == 0: out = c else: last_c_ord = self.ord[output[-1]] out_ord = self.decrement(c_ord, last_c_ord) out = self.rev_ord[out_ord] output += out first_letter_ord = self.ord[out] return output