def oracle_cbc_ecb(plaintext): # Generate random key key = urandom(16) # Alternative way # key = long_to_bytes(randbits(128)) --> Error sometimes it generates less bytes # Probably long_to_bytes didn't work properly # Instance secret_generator secrets_generator = SystemRandom() # Prepend and append chunk of 5 --> 10 bytes chunk = secrets_generator.randint(5, 10) plaintext = urandom(chunk) + plaintext chunk = secrets_generator.randint(5, 10) plaintext += urandom(chunk) # Choose to encrypt using CBC or ECB option = secrets_generator.randint(0, 1) if option == 0: cbc = CBC(key, blocksize) iv = urandom(16) return cbc.encrypt(iv, plaintext) else: pad = PKCS7(blocksize) ecb = AES.new(key, AES.MODE_ECB) return ecb.encrypt(pad.encode(plaintext))
def split(secret: str, recombination_threshold: int, num_shares: int) -> (Share, ...): """split secret into shares using Shamir's Secret Sharing Algorithm""" # https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing assert num_shares >= recombination_threshold > 1, 'Hmmm... invalid n of m specification' assert secret, 'Hmmm... need a secret to split' secret = secret.encode() secret_identifier = str(uuid4()) f_0 = int.from_bytes(secret, byteorder='big', signed=False) mersenne, modulus = _find_suitable_mersenne_prime(f_0) rand = SystemRandom() coefficients = (f_0, ) + tuple( rand.randint(1, modulus - 1) for _ in range(recombination_threshold - 1)) # value of polynomial defined by coefficients at x in modulo modulus def f_x(x: int) -> int: return sum((a * ((x**i) % modulus) % modulus) for i, a in enumerate(coefficients)) % modulus x_values = set() while len(x_values) < num_shares: x_values.add(rand.randint(1, 10**6)) return tuple( Share(id=secret_identifier, mersenne=mersenne, x=x, y=f_x(x)) for x in x_values)
def test__modulo_inverse(self): from secrets import SystemRandom rand = SystemRandom() for i in (32, 64, 128, 256): x = rand.randint(0, 2**i) _, p = cloak.secret_sharing._find_suitable_mersenne_prime(x) y = cloak.secret_sharing._modulo_inverse(x=x, modulus=p) self.assertEqual(1, (x * y) % p)
def system_random_without_seed(): system_random = SystemRandom() result = [system_random.randint(1, 10) for i in range(1000)] counter = Counter(result) for key, value in sorted(counter.items()): print(key, ': ', value)
def test__find_suitable_mersenne_prime(self): from secrets import SystemRandom rand = SystemRandom() for i in (32, 64, 128, 256): x = rand.randint(0, 2**i) m, p = cloak.secret_sharing._find_suitable_mersenne_prime(x) self.assertIsInstance(m, int) self.assertIsInstance(p, int) self.assertGreater(p, x) for m_ in (i for i in cloak.known_mersenne_primes if 100 < i < m): self.assertLess(cloak.mersenne_prime(m_), x) self.assertIn(m, cloak.known_mersenne_primes)
def test_mersenne_prime(self): from math import log2 from secrets import SystemRandom rand = SystemRandom() for x in tuple( rand.randint(1, 10 ^ 9) for _ in range(100)) + cloak.known_mersenne_primes[0:10]: if x in cloak.known_mersenne_primes: m = cloak.mersenne_prime(x) self.assertIsInstance(m, int) self.assertEqual(x, int(log2(m + 1))) else: with self.assertRaises(AssertionError): cloak.mersenne_prime(x)
def generate_password(length=9): """ Generate a random password suitable to be typed using alternated hands. """ rng = SystemRandom() right_hand = "23456qwertasdfgzxcvbQWERTASDFGZXCVB" left_hand = "789yuiophjknmYUIPHJKLNM" first_hand = rng.randint(0, 1) pw = [] for i in range(length): if (i + first_hand) % 2: pw.append(rng.choice(left_hand)) else: pw.append(rng.choice(right_hand)) return "".join(pw)
self.logger.info(e) raise SystemExit(0) if resp.status_code == 200: self.logger.info('Done!') else: self.logger.info('Error occurred!') def get_url(self, link: str): self.send_request(link) def sleep(self, t: int): self.logger.info(f'Waiting {t} seconds before next hit.') sleep(t) def close(self): self.session.close() self.logger.info("Finished!") if __name__ == "__main__": bot = HaxBot() urls = args.url for n, u in enumerate(urls): o = urlparse(u) if o.scheme: bot.get_url(u) if n != (len(urls) - 1): bot.sleep(random_generator.randint(20, 32)) bot.close()
# Formula for Affine decryption: P = a^-1 (C - b) mod 26, where P is plaintext, a is key1, C is cipher text and b is key2. def affine_decrypt(key1, key2, ciphertext): cursor = list() plaintext = list() for c in ciphertext: cursor.append((modinv(key1, 26) * (mapping_table[c] - key2)) % 26) for cur in cursor: for letter, num in mapping_table.items(): if num == cur: plaintext.append(letter) return ''.join(plaintext) if __name__ == "__main__": rng = SystemRandom() plaintext = input( "Enter your message here: ") # Change your plaintext here key1 = rng.randint(1, 25) # key1 is between 1 and 25. while modinv(key1, 26) == None: key1 = rng.randint(1, 25) key2 = rng.randint(0, 25) # key2 is between 1 and 25. print(f"Key1 is {key1}\n") print(f"Key2 is {key2}\n") print("Implementing Affine Cipher...\n") ciphertext = affine_enc(key1, key2, plaintext.lower()) print(f"Encrypted cipher text of {plaintext}: {ciphertext}\n") actual_plaintext = affine_decrypt(key1, key2, ciphertext) print(f"Decrypt {ciphertext}, the plaintext is {actual_plaintext}")
def generate_random_otp(): """OTP generated will be of 5 digits, and it's range will be 10000 to 99999 (including both). """ random = SystemRandom() return random.randint(10000, 99999)
class RPSAgent(object): def __init__(self, configuration): self.obs = None self.config = configuration self.history = pd.DataFrame( columns=["step", "action", "opponent_action"]) self.history.set_index("step", inplace=True) self.history = self.history.astype({ "action": np.int, "opponent_action": np.int }) # How the game would have happened if we always chose the actions selected by our agent self.alternate_history = pd.DataFrame( columns=["step", "action", "opponent_action"]) self.alternate_history.set_index("step", inplace=True) self.history = self.history.astype({ "action": np.int, "opponent_action": np.int }) self.step = 0 self.score = 0 self.random = SystemRandom() def agent(self, observation, configuration=None, history=None) -> Tuple[int, pd.DataFrame]: if self.random.randint(0, 10) == 7: # Change the random seed self.random = SystemRandom() if configuration is not None: self.config = configuration if history is not None: self.history = history self.obs = observation self.step = self.obs.step # Append the last action of the opponent to the history if self.step > 0: self.history.loc[self.step - 1, "opponent_action"] = self.obs.lastOpponentAction self.alternate_history.loc[ self.step - 1, "opponent_action"] = self.obs.lastOpponentAction self.score = get_score(self.history) if self.score - 20 > (1000 - self.step): # Don't waste computation time action = self.random.randint(0, 2) if self.random.randint(0, 10) <= 3: action = (action + 1) % SIGNS return action, history # Choose an action and append it to the history action = self.act() self.alternate_history.loc[self.step] = { "action": action, "opponent_action": None, } # Calculate the probability of a win for random play # Taken from https://www.kaggle.com/c/rock-paper-scissors/discussion/197402 win_prob = 0.5 + 0.5 * math.erf( ((observation.reward - 20) + 1) / math.sqrt( (2 / 3) * (1000 - observation.step))) if (win_prob >= 0.92 and get_score(self.history, 10) < 5 and self.random.randrange(0, 100) <= win_prob * 100): # Try to secure the win with random play action = self.random.randint(0, 2) if self.random.randint(0, 10) <= 3: action = (action + 2) % SIGNS elif get_score(self.alternate_history, 15) < -4: # If we got outplayed in the last 15 steps, play the counter of the chosen action´s counter with a # certain probability if self.random.randint(0, 100) <= 20: action = (action + 2) % SIGNS else: # Play randomly action = self.random.randint(0, 2) if self.random.randint(0, 10) <= 3: action = (action + 1) % SIGNS self.history.loc[self.step] = { "action": action, "opponent_action": None } return action, self.history def act(self) -> int: pass