コード例 #1
0
def form_req(seq):
    i = {}
    keyword = {
        'createorderwithmobile': 'seat',
        'createorder': 'seat',
    }
    for key in seq[1]:
        if isinstance(key, str):
            if key in data_dic:
                i.update({key: data_dic[key]})
            else:
                raise WrongData
        else:
            available = data_dic.get('available_seat')
            not_available = data_dic.get('not_available_seat')
            clear(available)
            clear(not_available)
            try:
                i.update({
                    keyword[seq[0]]:
                    str(
                        random.sample(available, key["seat"][0]) +
                        random.sample(not_available, key["seat"][1])).replace(
                            " ", "")
                })
            except:
                raise WrongData
    i.update(seq[2])
    reform = [seq[0], i, seq[3]]
    return reform
コード例 #2
0
    def test_hash_int_list(self):
        for i in range(1000):
            ls1 = sample(population=range(100, 999999999999), k=6)
            ls2 = sample(population=range(100, 999999999999), k=6)
            while ls1 == ls2:
                ls2 = sample(population=range(100, 999999999999), k=6)

            ds3 = hash_int(ls1)
            ds4 = hash_int(ls2)
            ds3c = hash_int(ls1)
            ds4c = hash_int(ls2)

            assert ds3 == ds3c
            assert ds4 == ds4c
            assert ds3 != ds4
コード例 #3
0
 def initialize_vault(self, mp):
     vd = VaultDistribution()
     if not os.path.exists(self.vault_fl):
         buf = rnd_source.read(hny_config.HONEY_VAULT_ENCODING_SIZE * 4)
         t_s = struct.unpack('!%sI' % hny_config.HONEY_VAULT_ENCODING_SIZE,
                             buf)
         self.H = t_s[:hny_config.HONEY_VAULT_GRAMMAR_SIZE]
         t_s = t_s[hny_config.HONEY_VAULT_GRAMMAR_SIZE:]
         self.S = [
             t_s[i * hny_config.PASSWORD_LENGTH:(i + 1) *
                 hny_config.PASSWORD_LENGTH] for i in range(self.s)
         ]
         #buf = struct.unpack('!%sI' % self.mpass_set_size, rnd_source.read(self.mpass_set_size))
         # self.machine_pass_set = \
         #     list(''.join(["{0:08b}".format(x)
         #                   for x in struct.unpack(
         #                     "%sB" % self.mpass_set_size, buf)]))
         # assert len(self.machine_pass_set) >= len(self.S)
         self.machine_pass_set = list('0' * (self.mpass_set_size * 8))
         k = int(math.ceil(hny_config.HONEY_VAULT_STORAGE_SIZE * \
                               hny_config.MACHINE_GENRATED_PASS_PROB/1000.0))
         for i in random.sample(range(hny_config.HONEY_VAULT_STORAGE_SIZE),
                                k):
             self.machine_pass_set[i] = '1'
         self.salt = rnd_source.read(8)
         self.save(mp)
     else:
         self.load(mp)
コード例 #4
0
ファイル: BlockUtil.py プロジェクト: evripidispar/CloudPDR
def pickDiffBlocks(numOfBlocks, common, totalBlocks):
	numDiff = numOfBlocks - len(common)
	
	blocks = range(totalBlocks)

	for block_index in xrange(numOfBlocks):
		if block_index in common:
			blocks.remove(block_index)

	a_diff = random.sample(blocks, numDiff)
	for block_index in a_diff:
		blocks.remove(block_index)


	b_diff = random.sample(blocks, numDiff)
	return (a_diff, b_diff)
コード例 #5
0
 def __init__(self, sender, receiver, data, *, part=1, count=1,
              pkgkey=None):
     """
     Instantiates a new object. This should not be invoked directly, use
     pack instead.
     @param sender: id of the sending client
     @type sender: int
     @param receiver: id of the receiving client
     @type receiver: int
     @param data: data of the PluginCommand
     @type data: str
     @param part: number of the splitted package, defaults to 1
     @type part: int
     @param count: count of splitted packages, defaults to 1
     @type count: int
     @param pkgkey: key of the package, defaults to None, then a random key
     is generated
     @type pkgkey: str
     """
     super().__init__()
     if pkgkey:
         self.pkgkey = pkgkey
     else:
         self.pkgkey = "".join(random.sample(PKGKEY_ALPHABET, 4))
     self.sender = sender
     self.receiver = receiver
     self.data = data
     self.part = part
     self.count = count
コード例 #6
0
 def pad_pkcs1(self, msg, btype=1):
     npad = self.k - 3 - len(msg)
     if btype == 1:
         padding = npad * b'\xff'
     elif btype == 2:
         padding = bytes(random.sample(range(1, 256), npad))
     return b'\x00' + bytes([btype]) + padding + b'\x00' + msg
コード例 #7
0
 def initialize_vault(self, mp):
     vd = VaultDistribution()
     if not os.path.exists(self.vault_fl):
         buf = rnd_source.read(hny_config.HONEY_VAULT_ENCODING_SIZE * 4)
         t_s = struct.unpack(
             '!%sI' % hny_config.HONEY_VAULT_ENCODING_SIZE, buf)
         self.H = t_s[:hny_config.HONEY_VAULT_GRAMMAR_SIZE]
         t_s = t_s[hny_config.HONEY_VAULT_GRAMMAR_SIZE:]
         self.S = [t_s[i*hny_config.PASSWORD_LENGTH:(i+1)*hny_config.PASSWORD_LENGTH]
                   for i in range(self.s)]
         #buf = struct.unpack('!%sI' % self.mpass_set_size, rnd_source.read(self.mpass_set_size))
         # self.machine_pass_set = \
         #     list(''.join(["{0:08b}".format(x) 
         #                   for x in struct.unpack(
         #                     "%sB" % self.mpass_set_size, buf)]))
         # assert len(self.machine_pass_set) >= len(self.S)
         self.machine_pass_set = list('0'*(self.mpass_set_size*8))
         k = int(math.ceil(hny_config.HONEY_VAULT_STORAGE_SIZE * \
                               hny_config.MACHINE_GENRATED_PASS_PROB/1000.0))
         for i in random.sample(range(hny_config.HONEY_VAULT_STORAGE_SIZE), k):
             self.machine_pass_set[i] = '1'
         self.salt = rnd_source.read(8)
         self.save(mp)
     else:
         self.load(mp)
コード例 #8
0
ファイル: tests.py プロジェクト: tompetersen/threshold-crypto
    def parameterizable_re_encryption_process_test(self, new_t: int, new_n: int):
        new_tp = ThresholdParameters(new_t, new_n)
        new_pk, new_shares = central.create_public_key_and_shares_centralized(self.cp, new_tp)

        assert new_pk != self.pk, "Public keys for new and old access structure are the same"

        # Without loss of generality we assume the lists to be ordered in a way, that remaining participants
        # are placed at the beginning of the list.
        # Choose t_max shares randomly from first min_n old and new shares as the shares of one distinct participant.
        max_t = max(self.tp.t, new_tp.t)
        min_n = min(self.tp.n, new_tp.n)
        t_old_shares = random.sample(self.shares[:min_n], k=max_t)
        t_old_shares_x = [share.x for share in t_old_shares]
        t_new_shares = random.sample(new_shares[:min_n], k=max_t)
        t_new_shares_x = [share.x for share in t_new_shares]

        partial_re_encrypt_keys = []
        for i, (s_old, s_new) in enumerate(zip(t_old_shares, t_new_shares)):
            old_lambda = central.lagrange_coefficient_for_key_share_indices(t_old_shares_x, t_old_shares_x[i], self.cp)
            new_lambda = central.lagrange_coefficient_for_key_share_indices(t_new_shares_x, t_new_shares_x[i], self.cp)
            partial_key = participant.compute_partial_re_encryption_key(s_old, old_lambda, s_new, new_lambda)
            partial_re_encrypt_keys.append(partial_key)

        re_encrypt_key = central.combine_partial_re_encryption_keys(partial_re_encrypt_keys,
                                                                    self.pk,
                                                                    new_pk,
                                                                    self.tp,
                                                                    new_tp)
        re_em = central.re_encrypt_message(self.em, re_encrypt_key)

        self.assertNotEqual(self.em, re_em)

        # successful decryption with t shares
        new_reconstruct_shares = random.sample(new_shares, new_tp.t)
        new_partial_decryptions = [participant.compute_partial_decryption(re_em, share) for share in new_reconstruct_shares]

        decrypted_message = central.decrypt_message(new_partial_decryptions, re_em, new_tp)
        self.assertEqual(self.message, decrypted_message)

        # failing decryption with t - 1 shares
        with self.assertRaises(ThresholdCryptoError) as dec_exception_context:
            less_reconstruct_shares = random.sample(new_shares, new_tp.t - 1)
            new_partial_decryptions = [participant.compute_partial_decryption(re_em, share) for share in less_reconstruct_shares]
            central._decrypt_message(new_partial_decryptions, re_em)

        self.assertIn("Message decryption failed", str(dec_exception_context.exception))
コード例 #9
0
    def __init__(self, network, net_id, vendors):
        Node.__init__(self, network, net_id)
        self.vendors = vendors

        self.valid_scripsIDs = sample(range(0, 0xFFFFFFFF), 1000)
        self.used_scripsIDs = []
        self.master_scrips = []  # length of ten
        self.master_customers = []  # length of ten
コード例 #10
0
ファイル: solve.py プロジェクト: defund/ctf
def query():
    p, q = random.sample(primes, 2)
    n = p * q
    e = 65537
    key = RSA.construct((n, e))
    cipher = PKCS1_OAEP.new(key)
    enc = cipher.encrypt(flag)
    return key, enc
コード例 #11
0
ファイル: crypt_gui.py プロジェクト: Electrostatus/Various
 def genKey(self):
     "generate a random key"
     n = self.keySizeSB.value()
     char = string.printable.rstrip()  #map(chr, range(256))
     while len(char) < n:
         char += char
     key = ''.join(random.sample(char, n))
     self.keyInput.setText(key)
コード例 #12
0
def generate_phrase_str(phrase, separator=DEFAULTS['separator']):
    phrase_str = ''
    while phrase:
        if len(phrase) == 1:
            phrase_str = phrase_str + phrase.pop(0)
        else:
            sep = sample(separator, 1)[0]
            phrase_str = phrase_str + phrase.pop(0) + sep
    return phrase_str
コード例 #13
0
ファイル: encryption.py プロジェクト: odd-meta/Empire
def generate_aes_key():
    """
    Generate a random new 128-bit AES key using Pycrypto's secure Random functions.
    """
    punctuation = '!#$%&()*+,-./:;<=>?@[\]^_`{|}~'
    return ''.join(
        random.sample(
            string.ascii_letters + string.digits +
            '!#$%&()*+,-./:;<=>?@[\]^_`{|}~', 32))
コード例 #14
0
 def certifying_client_key(self):
     TOKEN_CHAR_LIST = "abcdefghij!@#$%"
     passphrase = ''.join(random.sample(TOKEN_CHAR_LIST, 10))
     shared_key = hasher(passphrase)
     CertifiedKey = hasher(str(self.PUBLIC_KEY))
     print(" hash of your Key : " + str(CertifiedKey))
     if CertifiedKey:
         return (CertifiedKey)
     else:
         logging.log("Unable to certify key.", msg_type='ERROR')
コード例 #15
0
 def getSharedKey(self):
     TOKEN_CHAR_LIST = "abcdefghij!@#$%"
     passphrase = ''.join(random.sample(TOKEN_CHAR_LIST, 10))
     shared_key = hasher(passphrase)
     print("shared_key" + str(shared_key) + str(type(shared_key)))
     print("custemor_pub_key : " + str(self.custemor_pub_key) + str(type(self.custemor_pub_key)))
     EnSharedKey = RSA_.encrypt(self.custemor_pub_key, shared_key)
     if EnSharedKey:
         return (shared_key, EnSharedKey)
     else:
         logging.log("Unable to encrypt shared key with RSA.", msg_type='ERROR')
コード例 #16
0
    def generate_example(self):
        while True:
            example =  "".join(sample(self.example_words, self.min_num_words))

            try:
                self.validate(example)
                break
            except ValidationError:
                pass

        return example
コード例 #17
0
 def pack(cls, sender, receiver):
     """
     Creates a new keyrequest
     @param sender: the id of the sending client
     @type sender: int
     @param receiver: the id of the target client
     @type receiver: int
     @return: the created keyrequest command
     @rtype: _RequestKey
     """
     return _RequestKey(sender, receiver,
                        "".join(random.sample(PKGKEY_ALPHABET, 4)))
コード例 #18
0
    def getSharedKey(self):
        TOKEN_CHAR_LIST = "abcdefghij!@#$%"

        # Generate unique symmetric 10bit key for each client
        passphrase = ''.join(random.sample(TOKEN_CHAR_LIST, 10))
        shared_key = hasher(passphrase)
        EnSharedKey = RSA_.encrypt(self.PUBLIC_KEY, shared_key)
        if EnSharedKey:
            return (shared_key, EnSharedKey)
        else:
            logging.log("Unable to encrypt shared key with RSA.",
                        msg_type='ERROR')
コード例 #19
0
 def encryptToken(self, token):
     """
     Encrypts token, returning:
         (token_crypt, crypt_iv, crypt_key)
     where:
         token_crypt : encrypted token
         crypt_iv    : the initialization vector used for encryption
         crypt_key   : the encryption key used for encryption
     """
     if token is None:
         logger.error("AbstractServer.saveToken() :: ERROR, token is None; aborting...")
         raise ValueError("ERROR, token is None")
     crypt_key_default = '6xytURQ4JITKMhgN'
     crypt_key = self.Confighandler.get('crypt_key', '6xytURQ4JITKMhgN') # crypt key should generally be stored in the system config; different from the one where crypt_iv is stored...
     # Note: I'm pretty sure the initiation vector needs to be randomly generated on each encryption,
     # but not sure how to do this in practice... should the IV be saved for later decryption?
     # Probably only relevant for multi-message encrypted communication and not my simple use-case...?
     # crypt_iv = self.Confighandler.get('crypt_key', 'Ol6beVHM91ZBh7XP')
     # ok, edit: I'm generating a random IV on every new save; this can be "publically" readable...
     # But, it probably does not make a difference either way; the crypt_key is readable anyways...
     if crypt_key == crypt_key_default:
         new_crypt_key = "".join(crypt_random.sample(string.ascii_letters+string.digits, 16))
         if 'system' in self.Confighandler.Configs:
             self.Confighandler.setkey('crypt_key', new_crypt_key, 'system', autosave=True)
             crypt_key = new_crypt_key
             logger.info("System encryption key set to new random string of length %s", len(new_crypt_key))
         else:
             logger.info("Using default crypt_key for encryption. You should create a 'system' config file, \
                         optionally using labfluence --createconfig system.")
     else:
         logger.debug("Using crypt_key from confighandler...")
     crypt_iv = "".join(crypt_random.sample(string.ascii_letters+string.digits, 16))
     # Not exactly 128-bit worth of bytes since ascii_letters+digits is only 62 in length, but should be ok still; I want to make sure it is realiably persistable with yaml.
     cryptor = AES.new(crypt_key, AES.MODE_CFB, crypt_iv)
     token_crypt = cryptor.encrypt(token)
     logger.debug("Token successfully encrypted (using newly generated crypt iv)")
     return (token_crypt, crypt_iv, crypt_key)
コード例 #20
0
def gen_nonce_list(total, landmark_num):
    """ generate random indexes for all landmarks in a big list,
        and return it. Other code should slice the big list for
        each landmark in the following steps.
    total -- total number of tags
    landmark_num -- total number of landmarks
    """
    if total > 10000:
        n = total / 2000
    elif total > 1000:
        n = total / 200
    elif total > 100:
        n = max(landmark_num, total / 20)
    else:
        n = landmark_num
    return random.sample(range(total), n)
コード例 #21
0
ファイル: models.py プロジェクト: CampyDB/campy-server
    def create_new_user_id(session):
        """
        Create a new random user name by randomly sampling from a list of lowercase
        and uppercase letters and numbers in equal proportions using PyCrypto.
        A new user name will be unique and will not already exist in the DB.

        Args:
            session (sqlalchemy.session.Session): DB session

        Returns:
            str: Randomly generated user name that does not exist in the DB.
        """
        while True:
            new_user_name = ''.join(random.sample(LETTERS_NUMBERS_RANDOM_SAMPLING_SET, USER_NAME_LENGTH))
            if session.query(User).filter(User.name == new_user_name).count() == 0:
                return new_user_name
コード例 #22
0
ファイル: fragment.py プロジェクト: icaswell/sunchoke_bed
def interleave_messages(encrypted_and_fragmented_messages, size_constraint):

    size_constraint = _add_chaff(encrypted_and_fragmented_messages,
                                 size_constraint)

    #-------------------------------------------------------------------------------
    # this is done in an annoying way...
    messages = encrypted_and_fragmented_messages.values()
    # Get the indices of which message goes where:
    msg_idx = [
        msg_i for msg_i, frags in enumerate(messages)
        for _, frag in enumerate(frags)
    ]
    permuted_msg_idx = random.sample(msg_idx, len(msg_idx))
    permuted = reversed([messages[i].pop() for i in permuted_msg_idx])
    return reduce(lambda x, y: x + y, permuted)
コード例 #23
0
ファイル: pwgen.py プロジェクト: ponderstibbons/yspave
	def mkpass (self, entropy=None):
		if self.mode == 'external':
			return subprocess.check_output (self.call,shell=True)

		entropy=self.bits if not entropy else int(entropy)
		if self.mode in ['x','xkcd']:
			with open (self.dict) as f: lut = list(set(f.read().replace("'s",'').split()))
			lutsz = len (lut)
			return ' '.join (random.sample(lut,self.entropy_estimate(entropy,lutsz)))
		else:
			if self.mode in ['p','print']:
				lut = string.ascii_letters+string.digits+string.punctuation
			elif self.mode in ['a','alnum']:
				lut = string.ascii_letters+string.digits
			lutsz = len (lut)
			bytes_needed = self.entropy_estimate (entropy, lutsz)
			return ''.join (map (lambda x: lut[x%lutsz], bytearray(self.rng.read(bytes_needed))))
コード例 #24
0
def generate_password(length, allowed_chars=None, required_ranges=None):
    if not allowed_chars:
        allowed_chars = string.letters+string.digits
    # generate password
    password = [choice(allowed_chars) for _ in range(length)]

    # if certain ranges of characters are required (e.g A-Z), make sure they're each in the password
    if required_ranges:
        # find a target character in the password to hold a letter from each required range
        indexes = sample(range(len(password)), len(required_ranges))
        # put a letter from each required range in the selected location
        for index, required_range in zip(indexes, required_ranges):
            if required_range in named_ranges:
                required_range = named_ranges[required_range]
            password[index] = choice(required_range)

    return ''.join(password)
コード例 #25
0
ファイル: crypt.py プロジェクト: billychou/practice_demo
def cryptString(secret, plain):
    '''只有CM在使用,以后不要再使用'''
    obj = Blowfish.new(secret, Blowfish.MODE_ECB)
    randstring = str.join(
        '', random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890', 12))
    split = random.randrange(10) + 1
    s = randstring[:split] + ':valid:' + plain + ':valid:' + randstring[split:]
    length = len(s)

    l = length + 8 - (length % 8)
    padded = s + " " * (8 - length % 8)

    ciph = obj.encrypt(padded[:l])
    try:
        return b32encode(ciph)
    except NameError:
        return encodestring(ciph)
コード例 #26
0
def gen_masterpwd(length=128, public=None):
    """ Generates a random masterkey password and optionaly encrypt it

    Keywords arguments:
    length      -- The length of the masterkey password we want (default 128)
    public      -- The public key file to use to encrypt the masterkey password (default None)
    """

    items = string.printable.replace(' ', '')
    master = []

    for i in range(length):
        master.append(items[rand.randrange(0, len(items))])

    symbols = "".join(rand.sample(string.punctuation, 2))
    master.append(symbols)

    master = "".join(master)

    if public is not None:
        try:
            pub_file = open(public, 'r')

        except Exception as err:
            log.error("[gen_masterpwd] {}".format(err))

        else:
            pub_key = pub_file.read()
            rsa_key = rsa.importKey(pub_key)
            cipher = pkcs.new(rsa_key)
            try:
                ciph = cipher.encrypt(master.encode('utf-8'))
            except Exception as err:
                log.error(
                    "[gen_masterpwd] Error while encrypting the master password : {}"
                    .format(err))
            else:
                return base64.b64encode(ciph)
        finally:
            pub_file.close()

    else:
        return master
コード例 #27
0
def cryptString(secret, plain):
    '''只有CM在使用,以后不要再使用'''
    obj = Blowfish.new(secret, Blowfish.MODE_ECB)
    randstring = str.join(
        '',
        random.sample(
            'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890',
            12))
    split = random.randrange(10) + 1
    s = randstring[:split] + ':valid:' + plain + ':valid:' + randstring[split:]
    length = len(s)

    l = length + 8 - (length % 8)
    padded = s + " " * (8 - length % 8)

    ciph = obj.encrypt(padded[:l])
    try:
        return b32encode(ciph)
    except NameError:
        return encodestring(ciph)
コード例 #28
0
ファイル: genpiepie.py プロジェクト: cordor/genpiepie
def gen_masterpwd(length=128, public=None):
    """ Generates a random masterkey password and optionaly encrypt it

    Keywords arguments:
    length      -- The length of the masterkey password we want (default 128)
    public      -- The public key file to use to encrypt the masterkey password (default None)
    """

    items = string.printable.replace(' ', '')
    master = []

    for i in range(length):
        master.append(items[rand.randrange(0, len(items))])

    symbols = "".join(rand.sample(string.punctuation, 2))
    master.append(symbols)

    master = "".join(master)

    if public is not None:
        try:
            pub_file = open(public, 'r')

        except Exception as err:
            log.error("[gen_masterpwd] {}".format(err))

        else:
            pub_key = pub_file.read()
            rsa_key = rsa.importKey(pub_key)
            cipher = pkcs.new(rsa_key)
            try:
                ciph = cipher.encrypt(master.encode('utf-8'))
            except Exception as err:
                log.error("[gen_masterpwd] Error while encrypting the master password : {}".format(err))
            else:
                return base64.b64encode(ciph)
        finally:
            pub_file.close()

    else:
        return master
コード例 #29
0
    def pack(cls, sender, receiver, data):
        """
        Packs some string data to one or more PluginCommands
        @param sender: the own client id
        @type sender: int
        @param receiver: id of the target client
        @type receiver: int
        @param data: data to send
        @type data: str
        @return: a list of plugincommands
        @rtype: list(_GenericPluginCommand)
        """
        pkgcount = math.ceil(len(data) / MAX_CMD_SIZE)
        key = "".join(random.sample(PKGKEY_ALPHABET, 4))

        pkgs = []
        for i in range(pkgcount):
            pkgs.append(cls(sender, receiver,
                        data[i * MAX_CMD_SIZE:(i + 1) * MAX_CMD_SIZE],
                        part=i + 1, count=pkgcount, pkgkey=key))
        return pkgs
コード例 #30
0
    def generate_password(self):
        # select password length between min_length and max_length, with preference for PASSWORD_LENGTH
        length = max(
            min(PASSWORD_LENGTH,
                self.password_rules.get('max_length', PASSWORD_LENGTH)),
            self.password_rules.get('min_length', 0))

        # generate password from allowed_chars or PASSWORD_CHARS
        chars = self.password_rules.get('allowed_chars', PASSWORD_CHARS)
        password = ''.join(choice(chars) for _ in range(length))

        # if certain ranges of characters are required (e.g A-Z), make sure they're each in the password
        required_ranges = self.password_rules.get('required_ranges', [])
        if required_ranges:
            # find a target character in the password to hold a letter from each required range
            indexes = sample(range(len(password)), len(required_ranges))
            # put a letter from each required range in the selected location
            for index, required_range in zip(indexes, required_ranges):
                password[index] = choice(required_range)

        return password
コード例 #31
0
    def generate_password(self):
        # select password length between min_length and max_length, with preference for PASSWORD_LENGTH
        length = max(
                    min(
                        PASSWORD_LENGTH,
                        self.password_rules.get('max_length', PASSWORD_LENGTH)
                    ), self.password_rules.get('min_length', 0))

        # generate password from allowed_chars or PASSWORD_CHARS
        chars = self.password_rules.get('allowed_chars', PASSWORD_CHARS)
        password = ''.join(choice(chars) for _ in range(length))

        # if certain ranges of characters are required (e.g A-Z), make sure they're each in the password
        required_ranges = self.password_rules.get('required_ranges', [])
        if required_ranges:
            # find a target character in the password to hold a letter from each required range
            indexes = sample(range(len(password)), len(required_ranges))
            # put a letter from each required range in the selected location
            for index, required_range in zip(indexes, required_ranges):
                password[index] = choice(required_range)

        return password
コード例 #32
0
    def mkpass(self, entropy=None):
        if self.mode == 'external':
            return subprocess.check_output(self.call, shell=True)

        entropy = self.bits if not entropy else int(entropy)
        if self.mode in ['x', 'xkcd']:
            with open(self.dict) as f:
                lut = list(set(f.read().replace("'s", '').split()))
            lutsz = len(lut)
            return ' '.join(
                random.sample(lut, self.entropy_estimate(entropy, lutsz)))
        else:
            if self.mode in ['p', 'print']:
                lut = string.ascii_letters + string.digits + string.punctuation
            elif self.mode in ['a', 'alnum']:
                lut = string.ascii_letters + string.digits
            elif self.mode in ['n', 'numeric']:
                lut = string.digits
            lutsz = len(lut)
            bytes_needed = self.entropy_estimate(entropy, lutsz)
            return ''.join(
                map(lambda x: lut[x % lutsz],
                    bytearray(self.rng.read(bytes_needed))))
コード例 #33
0
def generate_passphrase(words=DEFAULTS["words"],
                        length=DEFAULTS["length"],
                        separator=DEFAULTS['separator'],
                        addnum=False,
                        caps=False):
    phrase = []
    for _ in range(words):
        word = sample(WORD_LIST, 1)[0]
        if caps:
            if randint(0,1):
                phrase.append(word.upper())
            else:
                phrase.append(word)
        else:
            phrase.append(word)
    if addnum: 
        num = str(randint(0, 9999)).rjust(4, '0')
        phrase.insert(randint(0,len(phrase)),num)

    phrase_str = generate_phrase_str(phrase, separator)
    if len(phrase_str) >= length:
        return phrase_str
    else:
        generate_passphrase(words, length, separator, addnum, caps)
コード例 #34
0
ファイル: test_random.py プロジェクト: hfalcic/google-gdata
 def runTest(self):
     """Crypto.Random.new()"""
     # Import the Random module and try to use it
     from Crypto import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Crypto.Random import random
     x = random.getrandbits(16*8)
     y = random.getrandbits(16*8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x>y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1,10):
         x = random.randrange(start,stop,step)
         y = random.randrange(start,stop,step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1,2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start,stop)
     y = random.randint(start,stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1,1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = list(range(10000))
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
     self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = list(range(500))
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
        self.assertEqual(seq[i] in x, True)
        self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "1")
     self.assertRaises(TypeError, random.shuffle, (1,2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
         # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1,2,3), 1)
     self.assertEqual(z[0] in (1,2,3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(list(range(3)), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
             z = random.sample(b("123"), 1)
             self.assertEqual(z[0] in b("123"), True)
             z = random.sample(bytearray(b("123")), 1)
             self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
コード例 #35
0
ファイル: cdkey.py プロジェクト: 24678/ds_mod_tools
from Crypto.Random import random # This is supposed to be a cryptographically strong version of Python's standard "random" module
import os, sys, argparse
from clint import textui

parser = argparse.ArgumentParser()
parser.add_argument( '-keylen', type=int, action="store", required=True )
parser.add_argument( '-numkeys', type=int, nargs=1, required=True )
parser.add_argument( '-characterset', action="store", required=True )
args = parser.parse_args()

if os.path.exists( args.characterset ):
    args.characterset = open( args.characterset, "r" ).read().strip()

sys.stderr.write( "The key space has a total of {0} keys".format( pow( len( args.characterset ), args.keylen ) ) )
keylen = args.keylen

for i in textui.progress.bar( xrange( args.numkeys[0] ) ):
    key = ''.join( random.sample( args.characterset, keylen ) )
    key = '-'.join( [ key[i:i+4] for i in xrange( 0, keylen, 4 ) ] )
    print key
コード例 #36
0
# selected password will automatically be selected
# or it can be set to any bash acceptable character
# set for a password.

STAGING_KEY = os.getenv('STAGING_KEY', "BLANK")
punctuation = '!#%&()*+,-./:;<=>?@[]^_{|}~'

# otherwise prompt the user for a set value to hash for the negotiation password
if STAGING_KEY == "BLANK":
    choice = raw_input(
        "\n [>] Enter server negotiation password, enter for random generation: "
    )
    if choice == "":
        # if no password is entered, generation something random
        STAGING_KEY = ''.join(
            random.sample(string.ascii_letters + string.digits + punctuation,
                          32))
    else:
        STAGING_KEY = hashlib.md5(choice).hexdigest()
elif STAGING_KEY == "RANDOM":
    STAGING_KEY = ''.join(
        random.sample(string.ascii_letters + string.digits + punctuation, 32))

# the installation path for Empire, defaults to auto-calculating it
#   set manually if issues arise
currentPath = os.path.dirname(os.path.realpath(__file__))
empireIndex = currentPath.rfind("Empire")
if empireIndex < 0:
    empireIndex = currentPath.rfind("empire")
if empireIndex < 0:
    INSTALL_PATH = "/".join(os.getcwd().split("/")[0:-1]) + "/"
else:
コード例 #37
0
 def __getOrganismsToReproduce(self):
      return  random.sample(self.organisms, (2 * int(((len(self.organisms) - 1) / 3))))
コード例 #38
0
ファイル: keygen.py プロジェクト: bbengfort/flashcube
def saltpair(num=12):

    chars = string.ascii_lowercase + string.ascii_uppercase
    chars += chars # Allows for duplicate char pair (e.g. 'DD')
    return [''.join(random.sample(chars, 2)) for x in xrange(num)]
コード例 #39
0
 def runTest(self):
     """Crypto.Random.new()"""
     # Import the Random module and try to use it
     from Crypto import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Crypto.Random import random
     x = random.getrandbits(16 * 8)
     y = random.getrandbits(16 * 8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x > y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1, 10):
         x = random.randrange(start, stop, step)
         y = random.randrange(start, stop, step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1, 2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start, stop)
     y = random.randint(start, stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1, 1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = list(range(10000))
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1, 2, 3)) in (1, 2, 3), True)
     self.assertEqual(random.choice([1, 2, 3]) in [1, 2, 3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(
             random.choice(bytearray(b('123'))) in bytearray(b('123')),
             True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = list(range(500))
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
         self.assertEqual(seq[i] in x, True)
         self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "1")
     self.assertRaises(TypeError, random.shuffle, (1, 2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
     # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1, 2, 3), 1)
     self.assertEqual(z[0] in (1, 2, 3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(list(range(3)), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
         z = random.sample(b("123"), 1)
         self.assertEqual(z[0] in b("123"), True)
         z = random.sample(bytearray(b("123")), 1)
         self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
コード例 #40
0
 def gen_nonce(self):
     TOKEN_CHAR_LIST = "abcdefghij!@#$%"
     self.nonce = ''.join(random.sample(TOKEN_CHAR_LIST, 10))
     self.KEYNonce =hasher(self.nonce + self.KEY)
コード例 #41
0
def chooseRandomBlocksForRandomChallenge(totalBlocks, precentage):
    if totalBlocks <= 10000:
        return xrange(totalBlocks)
    else:
        k = random.sample(xrange(totalBlocks), int(totalBlocks*precentage))
        return set(k)
コード例 #42
0
ファイル: encryption.py プロジェクト: 0day29/Empire
def generate_aes_key():
    """
    Generate a random new 128-bit AES key using Pycrypto's secure Random functions.
    """
    punctuation = '!#$%&()*+,-./:;<=>?@[\]^_`{|}~'
    return ''.join(random.sample(string.ascii_letters + string.digits + '!#$%&()*+,-./:;<=>?@[\]^_`{|}~', 32))
コード例 #43
0
ファイル: challenge47.py プロジェクト: 5l1v3r1/ctf-tools-5
def randnonzerobytes(k):
    return bytes(random.sample(range(1, 256), k))
コード例 #44
0
def rand_num_list(n, total):
    dividers = sorted(random.sample(xrange(1, total), n - 1))
    return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
コード例 #45
0
ファイル: BlockUtil.py プロジェクト: evripidispar/CloudPDR
def pickCommonBlocks(numOfBlocks, numOfCommon):
	common = random.sample(xrange(numOfBlocks), numOfCommon)
	return common
コード例 #46
0
def get_rand_keycode() :
    keycode_size = 32
    return random.sample(range(255), keycode_size)
コード例 #47
0
# Staging Key is set up via environmental variable
# or via command line. By setting RANDOM a randomly
# selected password will automatically be selected
# or it can be set to any bash acceptable character
# set for a password.

STAGING_KEY = os.getenv('STAGING_KEY', "BLANK")
punctuation = '!#%&()*+,-./:;<=>?@[]^_{|}~'

# otherwise prompt the user for a set value to hash for the negotiation password
if STAGING_KEY == "BLANK":
    choice = raw_input("\n [>] Enter server negotiation password, enter for random generation: ")
    if choice == "":
        # if no password is entered, generation something random
        STAGING_KEY = ''.join(random.sample(string.ascii_letters + string.digits + punctuation, 32))
    else:
        STAGING_KEY = hashlib.md5(choice).hexdigest()
elif STAGING_KEY == "RANDOM":
    STAGING_KEY = ''.join(random.sample(string.ascii_letters + string.digits + punctuation, 32))

# the installation path for Empire, defaults to auto-calculating it
#   set manually if issues arise
currentPath = os.path.dirname(os.path.realpath(__file__))
empireIndex = currentPath.rfind("Empire")
if empireIndex < 0:
    empireIndex = currentPath.rfind("empire")
if empireIndex < 0:
    INSTALL_PATH = "/".join(os.getcwd().split("/")[0:-1])+"/"
else:
    endIndex = currentPath.find("/", empireIndex)
コード例 #48
0
# Staging Key is set up via environmental variable
# or via command line. By setting RANDOM a randomly
# selected password will automatically be selected
# or it can be set to any bash acceptable character
# set for a password.

STAGING_KEY = os.getenv('STAGING_KEY', "BLANK")
punctuation = '!#%&()*+,-./:;<=>?@[]^_{|}~'

# otherwise prompt the user for a set value to hash for the negotiation password
if STAGING_KEY == "BLANK":
    choice = raw_input("\n [>] Enter server negotiation password, enter for random generation: ")
    if choice == "":
        # if no password is entered, generation something random
        STAGING_KEY = ''.join(random.sample(string.ascii_letters + string.digits + punctuation, 32))
    else:
        STAGING_KEY = hashlib.md5(choice).hexdigest()
elif STAGING_KEY == "RANDOM":
    STAGING_KEY = ''.join(random.sample(string.ascii_letters + string.digits + punctuation, 32))

# the installation path for Empire, defaults to auto-calculating it
#   set manually if issues arise
currentPath = os.path.dirname(os.path.realpath(__file__))
empireIndex = currentPath.rfind("Empire")
if empireIndex < 0:
    empireIndex = currentPath.rfind("empire")
if empireIndex < 0:
    INSTALL_PATH = "/".join(os.getcwd().split("/")[0:-1])+"/"
else:
    endIndex = currentPath.find("/", empireIndex)
コード例 #49
0
ファイル: scriptify.py プロジェクト: codeSamuraii/Scriptify
                       tag='None',
                       bin="None")

    if args.compress:
        if args.compress >= 2:
            comp_level = 9
        else:
            comp_level = 6
        print(f"* Compressing (level {comp_level})...")
        file_buffer = compress(file_buffer, preset=comp_level)
        substitutes['compression'] = 'True'

    if args.password is not None:
        print("* Encrypting...")
        if args.password == '':
            password = ''.join(random.sample(string.hexdigits, 12))
        else:
            password = args.password
        print("  ->", password)

        hasher = SHA3_256.new(password.encode('utf-8'))
        key_hash = hasher.digest()

        aes_cipher = AES.new(key_hash, AES.MODE_EAX)
        file_buffer, tag = aes_cipher.encrypt_and_digest(file_buffer)
        nonce = aes_cipher.nonce

        substitutes['aes_enc'] = 'True'
        substitutes['tag'] = repr(tag)
        substitutes['nonce'] = repr(nonce)