def main(): # Normalize arguments args = docopt(__doc__) word_count = int(args['--length']) # Read and transform dictionary file if args['--dictionary']: dict_path = args['--dictionary'] else: dict_path = os.path.join(os.path.dirname(__file__), 'words.txt') dictionary = [w for w in [l.strip() for l in open(dict_path)] if w] if args['--truncate']: dictionary = dictionary[:int(args['--truncate'])] elif not args['--dictionary']: # Default truncation for built-in dictionary dictionary = dictionary[:8192] # Basic entropy calculation if args['--uncontrolled']: entropy = math.log(math.pow(len(dictionary), word_count), 2) else: batch_size = len(dictionary) // word_count entropy = math.log(math.pow(batch_size, word_count) * math.factorial(word_count), 2) if args['--verbose']: print("Pessimistic password entropy: %.1f bits" % entropy) print("Approximate time to crack at 20k/s: %.1f days" % (math.pow(2, entropy) / 20000 / 60 / 60 / 24)) # Generate password rng = SystemRandom() if args['--uncontrolled']: # Select random words words = [rng.choice(dictionary) for i in range(word_count)] else: # Generate batches in random order batches = [dictionary[i*batch_size:(i+1)*batch_size] for i in range(word_count)] rng.shuffle(batches) # Select word from each batch words = [rng.choice(batches[i]) for i in range(word_count)] # Reveal to user print(" ".join(words)) if args['--complex']: print("Complexified: %s1." % "".join(words).capitalize())
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)
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default random.choice method. """ rand = SystemRandom() return ''.join(rand.choice(chars) for x in range(length))
def generate_token(request, length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth Json Web Token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default random.choice method. """ from django.conf import settings from jose import jwt rand = SystemRandom() secret = getattr(settings, 'SECRET_KEY') token = ''.join(rand.choice(chars) for x in range(length)) jwtted_token = jwt.encode({'token': token}, secret, algorithm='HS256') return jwtted_token
def authorization_url(self, **kwargs): """Generates an authorization URL. This is the first step in the OAuth 2.0 Authorization Flow. The user's browser should be redirected to the returned URL. This method calls :meth:`requests_oauthlib.OAuth2Session.authorization_url` and specifies the client configuration's authorization URI (usually Google's authorization server) and specifies that "offline" access is desired. This is required in order to obtain a refresh token. Args: kwargs: Additional arguments passed through to :meth:`requests_oauthlib.OAuth2Session.authorization_url` Returns: Tuple[str, str]: The generated authorization URL and state. The user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different :class:`Flow` instance to obtain the token, you will need to specify the ``state`` when constructing the :class:`Flow`. """ kwargs.setdefault("access_type", "offline") if self.autogenerate_code_verifier: chars = ascii_letters + digits + "-._~" rnd = SystemRandom() random_verifier = [rnd.choice(chars) for _ in range(0, 128)] self.code_verifier = "".join(random_verifier) if self.code_verifier: code_hash = hashlib.sha256() code_hash.update(str.encode(self.code_verifier)) unencoded_challenge = code_hash.digest() b64_challenge = urlsafe_b64encode(unencoded_challenge) code_challenge = b64_challenge.decode().split("=")[0] kwargs.setdefault("code_challenge", code_challenge) kwargs.setdefault("code_challenge_method", "S256") url, state = self.oauth2session.authorization_url( self.client_config["auth_uri"], **kwargs ) return url, state
def reset_piv(self): '''Resets YubiKey PIV app and generates new key for GAM to use.''' reply = str( input( 'This will wipe all PIV keys and configuration from your YubiKey. Are you sure? (y/N) ' ).lower().strip()) if reply != 'y': sys.exit(1) try: conn = self._connect() with conn: piv = PivSession(conn) piv.reset() rnd = SystemRandom() pin_puk_chars = string.ascii_letters + string.digits + string.punctuation new_puk = ''.join(rnd.choice(pin_puk_chars) for _ in range(8)) new_pin = ''.join(rnd.choice(pin_puk_chars) for _ in range(8)) piv.change_puk('12345678', new_puk) piv.change_pin('123456', new_pin) print(f'PIN set to: {new_pin}') piv.authenticate(MANAGEMENT_KEY_TYPE.TDES, DEFAULT_MANAGEMENT_KEY) piv.verify_pin(new_pin) print('YubiKey is generating a non-exportable private key...') pubkey = piv.generate_key(SLOT.AUTHENTICATION, KEY_TYPE.RSA2048, PIN_POLICY.ALWAYS, TOUCH_POLICY.NEVER) now = datetime.datetime.utcnow() valid_to = now + datetime.timedelta(days=36500) subject = 'CN=GAM Created Key' piv.authenticate(MANAGEMENT_KEY_TYPE.TDES, DEFAULT_MANAGEMENT_KEY) piv.verify_pin(new_pin) cert = generate_self_signed_certificate( piv, SLOT.AUTHENTICATION, pubkey, subject, now, valid_to) piv.put_certificate(SLOT.AUTHENTICATION, cert) piv.put_object(OBJECT_ID.CHUID, generate_chuid()) except ValueError as err: controlflow.system_error_exit(8, f'YubiKey - {err}')
def _generate_key(self): system_rand = SystemRandom() # generates random numbers from sources provided by the operating system self.key_size = system_rand.choice(SESSION_KEY_SIZES) session_key = system_rand.getrandbits(self.key_size) self.session_key = session_key.to_bytes(self.key_size // 8, byteorder='little')
"Safari/537.36 Edg/86.0.597.0", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" ] referrer_list = [ 'https://www.google.com/', 'https://www.google.co.in/', 'https://duckduckgo.com/', 'https://www.bing.com/', 'https://yandex.com/', 'https://en.wikipedia.org/', 'https://www.quora.com/', 'https://www.facebook.com/', 'https://www.feedspot.com/', 'https://www.reddit.com', 'https://medium.com/', 'https://www.youtube.com/', 'https://in.pinterest.com/', 'https://pinterest.com/' ] random_generator = SystemRandom() default_header = { 'User-Agent': random_generator.choice(u_a_list), 'Referrer': random_generator.choice(referrer_list) } class HaxBot(object): def __init__(self, log_level_file=logging.DEBUG, log_level_stream=logging.INFO): self.logger = logging.getLogger("Hax Bot") self.logger.setLevel(logging.DEBUG) if not path.isdir(log_dir): mkdir(log_dir) log_filename: str = path.join(log_dir, 'hax_bot.log') fh = logging.FileHandler(filename=log_filename) fh.setLevel(log_level_file)
def random_str(size: int) -> str: """ generate string of letters and digits of size length""" rand = SystemRandom() chars = ascii_letters + digits return u''.join(rand.choice(chars) for _ in range(size))
def generate_code(length=8): sr = SystemRandom() random_list = [sr.choice(ascii_lowercase + digits) for i in range(length)] return ''.join(random_list)
def __init__(self, name: str, age: int, sex: str): rand = SystemRandom() self.name = name self.age = age self.sex = sex self.UID = "%s%d" % (name[:4], rand.choice(range(1010, 9090)))
parser.add_argument("-a", action='store_true', help="Have lowercase characters in the passwrod") parser.add_argument("-A", action='store_true', help="Have uppercase characters in the passwrod") parser.add_argument("-s", action='store_true', help="Have symbols in the passwrod") parser.add_argument("-l", type=int, metavar="length", help="The length of password", default=16) command = parser.parse_args() r = SystemRandom() password = [] valid_chars = '' if command.n: valid_chars += digits if command.a: valid_chars += ascii_lowercase if command.A: valid_chars += ascii_uppercase if command.s: valid_chars += punctuation if not valid_chars: valid_chars = digits print("".join([r.choice(valid_chars) for i in range(command.l)]))