Example #1
0
    def generate_config(self, env_script, start_script, server_cert=None):
        """Generates the plugin configuration file

        Parameters
        ----------
        env_script : str
            The CLI call used to load the environment in which the plugin is
            installed
        start_script : str
            The script used to start the plugin
        server_cert : str, optional
            If the Qiita server used does not have a valid certificate, the
            path to the Qiita certificate so the plugin can connect over
            HTTPS to it
        """
        logger.debug('Entered BaseQiitaPlugin.generate_config()')
        sr = SystemRandom()
        chars = ascii_letters + digits
        client_id = ''.join(sr.choice(chars) for i in range(50))
        client_secret = ''.join(sr.choice(chars) for i in range(255))

        server_cert = server_cert if server_cert else ""

        with open(self.conf_fp, 'w') as f:
            f.write(CONF_TEMPLATE % (self.name, self.version, self.description,
                                     env_script, start_script,
                                     self._plugin_type, self.publications,
                                     server_cert, client_id, client_secret))
Example #2
0
def insert_special_char(word, specials=SPECIAL_CHARS, rnd=None):
    """Insert a char out of `specials` into `word`.

    `rnd`, if passed in, will be used as a (pseudo) random number
    generator. We use `.choice()` only.

    Returns the modified word.
    """
    if rnd is None:
        rnd = SystemRandom()
    char_list = list(word)
    char_list[rnd.choice(range(len(char_list)))] = rnd.choice(specials)
    return ''.join(char_list)
    def createUserSessionKey(org, username, sessionId,
                             consistency=ConsistencyLevel.LOCAL_QUORUM,
                             session=None):
        """
        Create a session key record in the usersessionkeys table for the given
        user session

        :org:
            Name of organization for the user
        :username:
            Name of the user
        :sessionid:
            ID of the session to create a key for
        """
        charList = (list(range(48, 58)) +  # Numbers
                    list(range(65, 91)) +  # Uppercase
                    list(range(97, 123)))  # Lowercase
        sysrand = SystemRandom()
        sessionKey = ''.join(
            chr(sysrand.choice(charList))
            for i in range(64))
        try:
            createUserSessionKeyQuery = CassandraCluster.getPreparedStatement(
                """
                INSERT INTO usersessionkeys ( sessionkey, org, username,
                    sessionid )
                VALUES ( ?, ?, ?, ? )
                """, keyspace=session.keyspace)
            createUserSessionKeyQuery.consistency_level = consistency
            session.execute(createUserSessionKeyQuery,
                            (sessionKey, org, username, sessionId))
            return sessionKey
        except Exception as e:
            log.critical("Exception in AuthDB.createUserSessionKey: %s" % (e,))
Example #4
0
def random_password(description, min_chars=10, max_chars=20):
    """
    Creates a random password from uppercase letters, lowercase letters and
    digits with a length between min_chars and max_chars
    """

    # Open saved passwords file or create new one.
    try:
        fh = open("info/passwords.json", "r+")
        passwords = json.load(fh)
    except IOError:
        fh = open("info/passwords.json", "w+")
        passwords = {}

    # Return password if it exists already
    if description in passwords:
        fh.close()
        return passwords[description]

    # Create new password if it does not exist
    else:
        seeded_random = SystemRandom()
        chars = ascii_letters + digits
        password_length = seeded_random.randint(min_chars, max_chars)
        password = "".join(seeded_random.choice(chars) for _ in range(password_length))
        passwords[description] = password
        fh.seek(0)
        json.dump(passwords, fh, indent=4)
        fh.close()

        return password
Example #5
0
def generate(word_list, words=5, specials=0):
    rnd = SystemRandom()
    words = [ rnd.choice(word_list) for _ in range(words) ]

    # Insert at most options.special special characters. This is not
    # exactly the procedure described in the Diceware web page, because
    # this handles the case where there are more than 6 words in the
    # passphrase and more than 6 characters in the word.
    if specials:
        split_words = [ map(None, x) for x in words ]
        for _ in range(specials):
            # i is the index of the word in which the special character
            # replacement takes place.
            i = rnd.randrange(len(split_words))

            # j is the index of the character to be replaced with a special
            # character.
            j = rnd.randrange(len(split_words[i]))

            # k is the index of the special character
            k = rnd.randrange(len(SPECIAL_CHARS))

            # Split to individual characters, replace the k'th char, unsplit
            split_words[i][j] = SPECIAL_CHARS[k]

        with_specials = [ "".join(x) for x in split_words ]
    else:
        with_specials = words

    return words, with_specials
Example #6
0
	def generate_password(self):
		import string
		from random import SystemRandom
		rnd = SystemRandom() # use SystemRandom to get real random numbers
		chars = string.letters + string.digits
		length = 20
		return "".join(rnd.choice(chars) for _ in range(length))
Example #7
0
def get_encrypted_password(password, hashtype='sha512', salt=None):

    # TODO: find a way to construct dynamically from system
    cryptmethod= {
        'md5':      '1',
        'blowfish': '2a',
        'sha256':   '5',
        'sha512':   '6',
    }

    if hashtype in cryptmethod:
        if salt is None:
            r = SystemRandom()
            if hashtype in ['md5']:
                saltsize = 8
            else:
                saltsize = 16
            salt = ''.join([r.choice(string.ascii_letters + string.digits) for _ in range(saltsize)])

        if not HAS_PASSLIB:
            if sys.platform.startswith('darwin'):
                raise errors.AnsibleFilterError('|password_hash requires the passlib python module to generate password hashes on Mac OS X/Darwin')
            saltstring =  "$%s$%s" % (cryptmethod[hashtype],salt)
            encrypted = crypt.crypt(password, saltstring)
        else:
            if hashtype == 'blowfish':
                cls = passlib.hash.bcrypt;
            else:
                cls = getattr(passlib.hash, '%s_crypt' % hashtype)

            encrypted = cls.encrypt(password, salt=salt)

        return encrypted

    return None
Example #8
0
    def __init__(self, config, director, scheduler, _reactor=reactor):
        self._reactor = reactor
        self.director = director
        self.scheduler = scheduler

        self.config = config
        self.measurement_path = FilePath(config.measurements_directory)

        # We use a double submit token to protect against XSRF
        rng = SystemRandom()
        token_space = string.letters+string.digits
        self._xsrf_token = b''.join([rng.choice(token_space)
                                    for _ in range(30)])

        self._director_started = False
        self._is_initialized = config.is_initialized()

        # We use exponential backoff to trigger retries of the startup of
        # the director.
        self._director_startup_retries = 0
        # Maximum delay should be 30 minutes
        self._director_max_retry_delay = 30*60

        self.status_poller = LongPoller(
            self._long_polling_timeout, _reactor)
        self.director_event_poller = LongPoller(
            self._long_polling_timeout, _reactor)

        # XXX move this elsewhere
        self.director_event_poller.start()
        self.status_poller.start()

        self.director.subscribe(self.handle_director_event)
        if self._is_initialized:
            self.start_director()
Example #9
0
    def __init__(self, known_pattern=None, session=db_session):
        '''Instantiates a color game based on a random color pattern.

        If known_pattern is specified, this color pattern is used to create the game
        instead of a random pattern.  This should only be used for testing purposes.

        If session is specified, this DB session is used instead of the standard session.

        :param known_pattern: a list (or tuple) of one-letter colors (default: None)
        :param session: the DB session (default: standard color game session)
        '''
        # Make sure to cleanup database resources on exit
        register(self._cleanup)

        # Set up DB session
        self.s = session

        if known_pattern is None:
            sr = SystemRandom()
            self.pattern = [sr.choice(colors_short) for _ in range(PATTERN_LENGTH)]
        else:
            self.pattern = known_pattern
        self.pattern_set = set(self.pattern)
        self.game = ColorGame(pattern=ColorPattern(self.pattern))
        self.s.add(self.game)
        self.s.commit()
Example #10
0
def get_passphrase(wordnum=6, specialsnum=1, delimiter='', lang='en',
                   capitalized=True, wordlist_fd=None):
    """Get a diceware passphrase.

    The passphrase returned will contain `wordnum` words deliimted by
    `delimiter`.

    If `capitalized` is ``True``, all words will be capitalized.

    If `wordlist_fd`, a file descriptor, is given, it will be used
    instead of a 'built-in' wordlist (and `lang` will be
    ignored). `wordlist_fd` must be open for reading.

    The wordlist to pick words from is determined by `lang`,
    representing a language (unless `wordlist_fd` is given).

    """
    if wordlist_fd is None:
        wordlist_fd = open(get_wordlist_path(lang), 'r')
    word_list = get_wordlist(wordlist_fd)
    rnd = SystemRandom()
    words = [rnd.choice(word_list) for x in range(wordnum)]
    if capitalized:
        words = [x.capitalize() for x in words]
    result = delimiter.join(words)
    for _ in range(specialsnum):
        result = insert_special_char(result, rnd=rnd)
    return result
Example #11
0
	def createRandomToken(self):
		'''Create a random byte sequence to use as a repeating token'''
		r = SystemRandom()
		token = bytearray()
		numBytes = r.choice([3, 4, 5, 6])
		for i in range(numBytes):
			token.append(r.randrange(256))
		return token
Example #12
0
def create_token(length=10) -> bool:
    r = SystemRandom()
    token = ''.join([r.choice(string.ascii_lowercase+string.digits)
                         for _ in range(length)])
    new_token = RegistrationToken(token)
    
    if add_to_db(new_token):
        return new_token
Example #13
0
def generate_token(length=40, chars=UNICODE_ASCII_CHARACTER_SET):
    """Generates a non-guessable OAuth token

    OAuth 2.0 rfc does not specify the format of tokens except that they
    should be strings of random characters.
    """
    from random import SystemRandom
    rand = SystemRandom()
    return ''.join(rand.choice(chars) for x in range(length))
Example #14
0
def build_slug():
    """
    Returns a random string made from two words from the wordlist, such as "deter-trig".
    """
    wordlist = open(get_resource_path('wordlist.txt')).read().split('\n')
    wordlist.remove('')

    r = SystemRandom()
    return '-'.join(r.choice(wordlist) for x in range(2))
Example #15
0
def rndstr(size=16):
    """
    Returns a string of random ascii characters or digits

    :param size: The length of the string
    :return: string
    """
    _basech = string.ascii_letters + string.digits
    return "".join([rnd.choice(_basech) for _ in range(size)])
Example #16
0
def unreserved(size=64):
    """
    Returns a string of random ascii characters, digits and unreserved
    characters

    :param size: The length of the string
    :return: string
    """

    return "".join([rnd.choice(BASECH) for _ in range(size)])
Example #17
0
def randstring(length):
    """
    Return a random base62 string of the specified length.
    """
    alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    string = ""
    rng = SystemRandom()

    for i in range(length): string += rng.choice(alphabet)

    return string
Example #18
0
def save_new_secret_key(app):
    if not os.path.exists(LOCAL_CONFIG_FILE):
        copy_default_config_to_local()
    config = ConfigParser()
    config.read(LOCAL_CONFIG_FILE)
    rng = SystemRandom()
    secret_key = "".join([rng.choice(string.ascii_letters + string.digits) for _ in xrange(25)])
    app.config['SECRET_KEY'] = secret_key
    config.set('faraday_server', 'secret_key', secret_key)
    with open(LOCAL_CONFIG_FILE, 'w') as configfile:
        config.write(configfile)
Example #19
0
def set_secret(secret_filename):
    #this may throw an error if the file cannot be created, but that's OK, because 
    #then users will know to create it themselves
    f = open(secret_filename, "w")
    random = SystemRandom()
    letters = [chr(ord('A') + i) for i in xrange(26)]
    letters += [chr(ord('a') + i) for i in xrange(26)]
    letters += map(str, xrange(10))
    password = "".join([random.choice(letters) for i in xrange(10)])
    f.write(password)
    f.close()
    return password
Example #20
0
 def test_add(self):
     r = SystemRandom()
     for i in range(10):
         p = getRandPrime(5)
         while p <= 10:
             p = getRandPrime(5)
         e = ecc.ECC(r.randint(1, 100), r.randint(1, 100), p)
         all_points = list(e.listPointGenerator())
         for j in range(100):
             point1 = r.choice(all_points)
             point2 = r.choice(all_points)
             point = e.add(point1, point2)
             self.assertEqual(e.isInCurve(point), True)
Example #21
0
def auth_request(command, manager, options, logger):
    key = command.data
    variants = string.digits + string.ascii_letters
    rand = SystemRandom()
    size = len(key)
    client_solt = "".join(rand.choice(variants) for _ in range(size))
    content = "{}{}{}".format(options.get("secret"), client_solt, key)
    _hash = _cr_methods.get(options.get("hash_method"))
    if hash:
        content = _hash(bytes(content, "utf-8")).hexdigest()
    else:
        content = "no method"

    return command.create(target=CommandTargetType.auth, data="{}:{}".format(content, client_solt))
Example #22
0
def unambiguous_random_string(length):
    random = SystemRandom()
    ambiguous_chars = {
        'B', '8',
        'G', '6',
        'I', '1', 'l',
        '0', 'O', 'Q', 'D',
        'S', '5',
        'Z', '2'
    }
    choices = filter(lambda char: char not in ambiguous_chars,
                     string.digits + string.ascii_lowercase)

    return ''.join(random.choice(choices) for _ in xrange(length))
Example #23
0
def rand(end, start=None, step=None):
    r = SystemRandom()
    if isinstance(end, (int, long)):
        if not start:
            start = 0
        if not step:
            step = 1
        return r.randrange(start, end, step)
    elif hasattr(end, '__iter__'):
        if start or step:
            raise errors.AnsibleFilterError('start and step can only be used with integer values')
        return r.choice(end)
    else:
        raise errors.AnsibleFilterError('random can only be used on sequences and integers')
Example #24
0
class WordDB(object):
	"""
	Stores statistical markov chain patterns.
	"""
	
	learnfile = None
	
	def __init__(self):
		self.words = {}
		self.rnd = SystemRandom()
	
	def add_link(self, first, second):
		"""
		Adds a new link in the chain
		"""
		self.words.setdefault(first, list()).append(second)
	
	def get_next(self, first):
		"""
		Given the current node, pick the next one at random
		"""
		return self.rnd.choice(self.words[first])
	
	def generate(self, start=True, stop=False):
		word = self.get_next(start)
		while word != stop:
			yield word
			word = self.get_next(word)
	
	def genline(self, *p, **kw):
		return ' '.join(self.generate(*p, **kw))
	
	def add_line(self, line):
		prev = True # Start 
		#TODO: parse out puncuation as seperate nodes
		for w in line.split():
			self.add_link(prev, w)
			prev = w
		self.add_link(prev, False) #Finish
		
		if self.learnfile is not None:
			print repr(line)
			if line[-1] != '\n':
				line += '\n'
			self.learnfile.write(line)
	
	def load_linefile(self, file):
		for line in file:
			self.add_line(line)
Example #25
0
def grub2_hash(password, salt=None, iterations=10000):

    if salt is None:
        r = SystemRandom()
        salt = ''.join([r.choice(string.ascii_letters + string.digits) for _ in range(64)])

    if not HAS_PASSLIB:
        if sys.platform.startswith('darwin'):
            raise errors.AnsibleFilterError('|password_hash requires the passlib python module to generate password hashes on Mac OS X/Darwin')
        saltstring =  "$%s$%s" % (cryptmethod[hashtype],salt)
        encrypted = grub_pbkdf2_sha512.encrypt(password, salt=salt, rounds=iterations)
    else:
        encrypted = grub_pbkdf2_sha512.encrypt(password, salt=salt, rounds=iterations)

    return encrypted
Example #26
0
    def generate_question(self):
        """Generate random question."""
        generator = SystemRandom()
        operation = generator.choice(self.operators)
        first = generator.randint(self.interval[0], self.interval[1])
        second = generator.randint(self.interval[0], self.interval[1])

        # We don't want negative answers
        if operation == '-':
            first += self.interval[1]

        return ' '.join((
            str(first),
            operation,
            str(second)
        ))
Example #27
0
File: 54.py Project: tkosciol/qiita
def get_random_string(length):
    """Creates a random string of the given length with alphanumeric chars

    Parameters
    ----------
    length : int
        The desired length of the string

    Returns
    -------
    str
        The new random string
    """
    sr = SystemRandom()
    chars = ascii_letters + digits
    return ''.join(sr.choice(chars) for i in range(length))
Example #28
0
def random_salt_function(salt_len=12):
    """
    Creates random salt for password.

    :param salt_len: Length of salt. Default :data:`12`
    :type param: :class:`int`

    :return: Computed salt
    :rtype: str
    """
    charset = "abcdefghijklmnopqrstuxyz"
    charset = charset + charset.upper() + '1234567890'
    chars = []
    rand = SystemRandom()
    for _ in range(salt_len):
        chars.append(rand.choice(charset))
    return "".join(chars)
Example #29
0
def rand(environment, end, start=None, step=None, seed=None):
    if seed is None:
        r = SystemRandom()
    else:
        r = Random(seed)
    if isinstance(end, integer_types):
        if not start:
            start = 0
        if not step:
            step = 1
        return r.randrange(start, end + 1, step)
    elif hasattr(end, '__iter__'):
        if start or step:
            raise AnsibleFilterError('start and step can only be used with integer values')
        return r.choice(end)
    else:
        raise AnsibleFilterError('random can only be used on sequences and integers')
Example #30
0
    def save(self, *args, **kwargs):
        """
        get ordernumber from database sequence

        """
        if not self.token:
            gen = SystemRandom()
            self.token = ''.join(gen.choice(string.ascii_lowercase + string.digits) for x in range(64))

        if not self.ordernumber:
            from django.db import connection
            cursor = connection.cursor()

            cursor.execute("SELECT nextval('booking_ordernum_seq')")
            (ordernum,) = cursor.fetchone()
            self.ordernumber = str(ordernum)

        return super(Booking, self).save(*args, **kwargs)
Example #31
0
def generate_secure_random_string(N):
    cryptogen = SystemRandom()
    return ''.join(
        cryptogen.choice(string.ascii_uppercase + string.digits)
        for _ in range(N))
Example #32
0
 def gen_password(lenght=PWD_DEFAULT_LENGHT):
     sys_random = SystemRandom()
     return "".join(sys_random.choice(PWD_ALPHABET) for _ in range(lenght))
Example #33
0
#!/usr/bin/env python
import sys
from secret import flag, Primes
from random import SystemRandom
from Crypto.Util.number import *

Rand = SystemRandom()
p = Rand.choice(Primes)
q = Rand.choice(Primes)

n = p * q
e = 65537

sys.stdout.write("n = " + str(n) + '\n')
sys.stdout.write("e = " + str(e) + '\n')

sys.stdout.write("What do you want to Encrypt :: ")
sys.stdout.flush()

Inp = sys.stdin.readline().strip('\n')
if Inp == 'flag': Inp = flag

m = bytes_to_long(Inp)
c = pow(m, e, n)

sys.stdout.write("c = " + str(c) + '\n')
sys.stdout.flush()
sys.exit()
Example #34
0
import sqlite3
from random import SystemRandom

sql_connection = sqlite3.connect('website.db')
sql_cursor = sql_connection.cursor()

name = input('User Name: ')
bio = input('User Bio: ')
email = input('User Email: ')
rank = int(input('User Rank(0=no, 1=post restrict, 2=post free, 3=admin): '))
assert(name)
assert(bio)
assert(email)
assert(rank >= 0 and rank <= 3)

sr = SystemRandom()
salt = sr.choice(range(10000000,99999999))

sql_cursor.execute('insert into users values (?, ?, ?, ?, ?)', \
    (name, bio, str(salt), email, rank))
sql_connection.commit()


Example #35
0
def random_string(length):
    """Return a random string using the system's RNG."""
    rng = SystemRandom()
    return ''.join(rng.choice(string.printable) for i in range(length))
def _generate_pass():
    """Generate a random string of fixed length."""
    sysrand = SystemRandom()
    passwd_charset = string.ascii_letters + string.digits
    return ''.join([sysrand.choice(passwd_charset) for _ in range(32)])
Example #37
0
class PassphraseGenerator:

    PASSPHRASE_WORDS_COUNT = 7

    # Enforce a reasonable maximum length for passphrases to avoid DoS
    MAX_PASSPHRASE_LENGTH = 128
    MIN_PASSPHRASE_LENGTH = 20

    _WORD_LIST_MINIMUM_SIZE = 7300  # Minimum number of words in any of the word lists

    def __init__(self,
                 language_to_words: Dict[str, List[str]],
                 fallback_language: str = "en") -> None:
        # SystemRandom sources from the system rand (e.g. urandom, CryptGenRandom, etc)
        # It supplies a CSPRNG but with an interface that supports methods like choice
        self._random_generator = SystemRandom()

        self._fallback_language = fallback_language
        self._language_to_words = language_to_words
        if self._fallback_language not in self._language_to_words:
            raise InvalidWordListError(
                "Missing words list for fallback language '{}'".format(
                    self._fallback_language))

        # Validate each words list
        for language, word_list in self._language_to_words.items():
            # Ensure that there are enough words in the list
            word_list_size = len(word_list)
            if word_list_size < self._WORD_LIST_MINIMUM_SIZE:
                raise InvalidWordListError(
                    "The word list for language '{}' only contains {} long-enough words;"
                    " minimum required is {} words.".format(
                        language,
                        word_list_size,
                        self._WORD_LIST_MINIMUM_SIZE,
                    ))

            # Ensure all words are ascii
            try:
                " ".join(word_list).encode("ascii")
            except UnicodeEncodeError:
                raise InvalidWordListError(
                    "The word list for language '{}' contains non-ASCII words."
                )

            # Ensure that passphrases longer than what's supported can't be generated
            longest_word = max(word_list, key=len)
            longest_passphrase_length = len(
                longest_word) * self.PASSPHRASE_WORDS_COUNT
            longest_passphrase_length += self.PASSPHRASE_WORDS_COUNT  # One space between each word
            if longest_passphrase_length >= self.MAX_PASSPHRASE_LENGTH:
                raise InvalidWordListError(
                    "Passphrases over the maximum length ({}) may be generated:"
                    " longest word in word list for language '{}' is '{}' and number of words per"
                    " passphrase is {}".format(
                        self.MAX_PASSPHRASE_LENGTH,
                        language,
                        longest_word,
                        self.PASSPHRASE_WORDS_COUNT,
                    ))

            # Ensure that passphrases shorter than what's supported can't be generated
            shortest_word = min(word_list, key=len)
            shortest_passphrase_length = len(
                shortest_word) * self.PASSPHRASE_WORDS_COUNT
            shortest_passphrase_length += self.PASSPHRASE_WORDS_COUNT
            if shortest_passphrase_length <= self.MIN_PASSPHRASE_LENGTH:
                raise InvalidWordListError(
                    "Passphrases under the minimum length ({}) may be generated:"
                    " shortest word in word list for language '{}' is '{}' and number of words per"
                    " passphrase is {}".format(
                        self.MIN_PASSPHRASE_LENGTH,
                        language,
                        shortest_word,
                        self.PASSPHRASE_WORDS_COUNT,
                    ))

    @classmethod
    def get_default(cls) -> "PassphraseGenerator":
        global _current_generator
        if _current_generator is None:
            language_to_words = _parse_available_words_list(
                Path(config.SECUREDROP_ROOT))
            _current_generator = cls(language_to_words)
        return _current_generator

    @property
    def available_languages(self) -> Set[str]:
        return set(self._language_to_words.keys())

    def generate_passphrase(
            self,
            preferred_language: Optional[str] = None) -> DicewarePassphrase:
        final_language = preferred_language if preferred_language else self._fallback_language
        try:
            words_list = self._language_to_words[final_language]
        except KeyError:
            # If there is no wordlist for the desired language, fall back to the word list for the
            # default language
            words_list = self._language_to_words[self._fallback_language]

        words = [
            self._random_generator.choice(words_list)
            for _ in range(self.PASSPHRASE_WORDS_COUNT)
        ]  # type: List[str]
        return DicewarePassphrase(" ".join(words))
Example #38
0
def rndstr(size=6, chars=string.ascii_uppercase + string.digits):
    cryptogen = SystemRandom()
    return ''.join(cryptogen.choice(chars) for _ in range(size))
Example #39
0
def generate_password(length=8):
    rnd = SystemRandom()
    if length > 255:
        length = 255
    return "".join([rnd.choice(string.hexdigits) for _ in range(length)])
Example #40
0
def mksalt():
    """Generate SHA512 salt."""
    sr = SystemRandom()
    return '$6$' + ''.join(
        sr.choice(ascii_letters + digits + './') for char in range(16))
Example #41
0
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
    rand = SystemRandom()
    return ''.join(rand.choice(chars) for x in range(length))
Example #42
0
def znc_random(size=20):
    r = SystemRandom()
    return ''.join([r.choice(randbase) for _ in range(size)])
Example #43
0
#!/usr/bin/env python

{% from 'ip.sls' import external_ip %}

import os
from random import SystemRandom
random = SystemRandom()


all_words = file('/usr/share/dict/words').read().split()

random_word = lambda: random.choice(all_words)

def random_words(*dist):
    return ' '.join(random_word().capitalize().replace("'s", "")
                    for _ in xrange(weighted_choice(*dist)))

def weighted_choice(*dist):
    "For quick&dirtiness, weights must be integers."
    return random.choice(sum(([item] * weight for item, weight in dist), []))

def gen_cert_call():

    "Typical-ish parameters with some very unscientific randomization."

    args = {}
    args['keyalg'] = weighted_choice(('RSA', 4), ('EC', 1))

    # `man keytool`
    default_keysize = {'RSA': 2048, 'DSA': 1024, 'EC': 256}[args['keyalg']]
class SecretKeyGenerator:
    """SecretKeyGenerator class"""

    def __init__(self,
                 chars=properties.DEFAULT_CHARS,
                 file_name=properties.DEFAULT_FILE_NAME,
                 len_of_secret_key=properties.DEFAULT_LENGTH_OF_SECRET_KEY):
        self._chars = chars
        self._secret_key = ""
        self._len_of_secret_key = len_of_secret_key
        self._file_name = file_name
        self._system_random = SystemRandom()

    def _get_random_string(self):
        """
        Getting random string from self._chars.
            This random string is going to be the secret key
        """

        self._secret_key = ''.join(self._system_random.choice(self._chars)
                                   for _ in range(self._len_of_secret_key))

    def get_secret_key_from_file(self) -> str:
        """
        Getting secret key from a file

        Returns:
            secret_key: str
        """

        secret_key_file = open(self._file_name, 'r')
        secret_key = secret_key_file.readline()
        secret_key_file.close()
        return secret_key

    def _validate_secret_key(self, secret_key_to_validate: str):
        """
        Checking if the secret key is valid

        Args:
            secret_key_to_validate: str

        Raises:
            ValueError: if the secret key is invalid
        """

        if len(secret_key_to_validate) != self._len_of_secret_key:
            secret_key_file = open(self._file_name, 'w')
            secret_key_file.write("")
            secret_key_file.close()
            raise ValueError

    def _write_secret_key_to_file(self):
        """Writing the secret key to file"""

        secret_key_file = open(self._file_name, 'w')
        secret_key_file.write(self._secret_key)
        secret_key_file.close()

    def generate(self) -> str:
        """
        Processing generation of the secret key

        If the file already contains the correct secret key,
            then this method reads the secret key and returns it.
        If the file already contains an incorrect secret key,
            then this method deletes that file and creates a new one
            with a correct secret key.
        If no file was found,
            then this method creates a new file with the correct secret key.

        Returns:
            str: secret key
        """

        try:
            secret_key_from_file = self.get_secret_key_from_file()
            self._validate_secret_key(secret_key_from_file)
            self._secret_key = secret_key_from_file
        except (FileNotFoundError, ValueError):
            self._get_random_string()
            self._write_secret_key_to_file()

        return self._secret_key
Example #45
0
def crea_seed():
    alphabet = u'9ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    generator = SystemRandom()
    return(u''.join(generator.choice(alphabet) for _ in range(81)))
Example #46
0
 def on_start(self):
     cryptogen = SystemRandom()
     with open('users.json') as f:
         self.voters = json.loads(f.read())
     self.voter = cryptogen.choice(list(self.voters.items()))
Example #47
0
def generate_token(leng=64):
    sr = SystemRandom()
    return ''.join([
        sr.choice(string.ascii_lowercase + "0123456789") for i in range(leng)
    ])
Example #48
0
height = img.size[1]*2
print("{} x {}".format(width, height))
out_image_A = Image.new('1', (width, height))
out_image_B = Image.new('1', (width, height))
draw_A = ImageDraw.Draw(out_image_A)
draw_B = ImageDraw.Draw(out_image_B)

C0 = ((1, 0, 1, 0), (0, 1, 0, 1))
C1 = ((1, 0, 0, 1), (0, 1, 1, 0))

# Cycle through pixels
for x in xrange(0, int(width/2)):
    for y in xrange(0, int(height/2)):
        pixel = img.getpixel((x, y))
        if pixel == 0: #Pixel was black
            pat1 = random.choice(C1)
            draw_A.point((x*2, y*2), pat1[0])
            draw_A.point((x*2+1, y*2), pat1[1])
            draw_A.point((x*2, y*2+1), pat1[0])
            draw_A.point((x*2+1, y*2+1), pat1[1])

            pat2 = C1[1 - C1.index(pat1)]
            draw_B.point((x*2, y*2), pat2[2])
            draw_B.point((x*2+1, y*2), pat2[3])
            draw_B.point((x*2, y*2+1), pat2[2])
            draw_B.point((x*2+1, y*2+1), pat2[3])

        else : #Pixel was white
            pat1 = random.choice(C0)
            draw_A.point((x*2, y*2), pat1[0])
            draw_A.point((x*2+1, y*2), pat1[1])