Ejemplo n.º 1
0
def main():
    '''Main method
    '''
    rnd = SystemRandom()
    all_chars = printable.strip()
    key = ''.join([rnd.choice(all_chars) for _ in range(50)])
    with open(sys.argv[1], 'w') as fd_obj:
        fd_obj.write(key)
Ejemplo n.º 2
0
def main(stdscr):
    curses.curs_set(0)
    curses.init_pair(9, FG, BG)
    stdscr.bkgd(curses.color_pair(9))
    curses.start_color()
    size = stdscr.getmaxyx()

    PMatrix = collections.namedtuple("PMatrix",
                                ["foreground", "background", "dispense"])
    matr = PMatrix([], rand_string(printable.strip(), size[0] * size[1]), [])
    delta = 0
    lt = time.time()

    while 1:

        if CLEAR:
            stdscr.clear()
        else:
            stdscr.erase()

        now = time.time()
        delta += (now - lt) * UPDATES_PER_SECOND
        lt = now

        while delta >= 1:

            if stdscr.getmaxyx() != size:
                # In the event that the size of the screen has changed,
                # return from this function, effectively restarting
                # pmatrix.  
                return

            for _ in xrange(LETTERS_PER_UPDATE):
                matr.dispense.append(random.randint(0, size[1] - 1))

            for i, c in enumerate(matr.dispense):
                matr.foreground.append([0, c])
                if not random.randint(0, PROBABILITY):
                    del matr.dispense[i]

            for a, b in enumerate(matr.foreground):
                if b[0] < size[0] - 1:
                    stdscr.addstr(b[0], b[1],
                                    matr.background[b[0] * size[0] + b[1]],
                                    curses.color_pair(9))
                    b[0] += 1
                else:
                    # We cannot simply use `del b`. This is because using del
                    # on the local variable b will only remove its binding
                    # from the local namespace. We have to remove it directly
                    # from the list.  
                    del matr.foreground[a]

            delta -= 1
            stdscr.refresh()
Ejemplo n.º 3
0
def mutateUtterance(utt, botDir, percentage=10, variability=0):
    counter = 0
    keysAscii = list(printable.strip(whitespace))
    for position, letter in enumerate(utt):
        if not (letter.isspace()):
            mutate = choices([True, False],
                             [percentage / 100, 1 - percentage / 100])[0]
            if mutate:
                uttAux = list(utt)
                uttAux[position] = choice(keysAscii)
                utt = "".join(uttAux)
                if percentage > 1:
                    percentage += variability
                counter += 1
    statsDir = "/home/sergio/Desktop/proyecto/codigo/output/{}/".format(botDir)
    filename = "mutateUtteranceStats.txt"
    writeCounter(statsDir, filename, counter, len(utt))
    return utt
Ejemplo n.º 4
0
def make_pass(pool='chars',
              min_entropy=20,
              min_length=8,
              max_length=30):

    if min_length > max_length:
        raise Exception('min_length must be <= max_length.')

    if pool == 'chars':
        pool = printable.strip()

    elif pool == 'lowercase':
        pool = lowercase

    elif pool == 'alphanumeric':
        pool = ascii_letters + digits

    ind_entropy = log(len(pool), 2)
    min_length = max( int(ceil(min_entropy/ind_entropy)), min_length )

    # no reason to limit entropy by not allowing repeats (thus I use choice() instead of sample() )
    element_lst = [choice(pool) for i in xrange(min_length)]

    return ''.join(element_lst)
Ejemplo n.º 5
0
FORES = [
    Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA,
    Fore.CYAN, Fore.WHITE
]
BACKS = [
    Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA,
    Back.CYAN, Back.WHITE
]
STYLES = [Style.DIM, Style.NORMAL, Style.BRIGHT]

# This assumes your terminal is 80x24. Ansi minimum coordinate is (1,1).
MINY, MAXY = 1, 24
MINX, MAXX = 1, 80

# set of printable ASCII characters, including a space.
CHARS = ' ' + printable.strip()

PASSES = 1000


def main():
    colorama.init()
    pos = lambda y, x: Cursor.POS(x, y)
    # draw a white border.
    print(Back.WHITE, end='')
    print('%s%s' % (pos(MINY, MINX), ' ' * MAXX), end='')
    for y in range(MINY, 1 + MAXY):
        print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
    print('%s%s' % (pos(MAXY, MINX), ' ' * MAXX), end='')
    # draw some blinky lights for a while.
    for i in range(PASSES):
Ejemplo n.º 6
0
from warnings import warn
from string import (ascii_letters, printable, digits, whitespace)

OPEN_GROUP = "["
END_GROUP = "]"
CONCAT_GROUP = "+"
GROUP_SUFFIX_AST = "*"

GROUP_CATEGORIES = {
    "alpha": ascii_letters,
    "alphanum": ascii_letters + digits,
    "digits": digits,
    "underscore": "_",
    "whitespace": whitespace.replace("\n", ""),
    ".": printable.strip(),
    "string": printable.replace('"', ""),
    "nest": "|"
}


def parse_error(idx, string):
    raise SyntaxError(f"{idx+1}: {string}")


def category_error(category):
    raise ValueError(f"category {category!r} doesn't exist")


def internal_error(string):
    state_concatenating = False
    raise RuntimeError(string)
Ejemplo n.º 7
0
from pwn import *
from string import printable
from random import choice

char = printable.strip()
tmp = ''.join(choice(char) for i in range(1000))
string = tmp.encode('base64').replace('\n', '')


def kirim(isi):
    r.recvuntil(': ')
    r.sendline('ENCODE' + isi)
    return r.recvline().strip('\n')


cmpr = lambda x, y: dict(zip(x, y))
r = remote('127.0.0.1', 6000)
#r = process('python app.py')
flag = kirim('FLAG')
enc = kirim(' ' + tmp)
dic = cmpr(enc, string)

print ''.join(dic[i] for i in flag).decode('base64')
Ejemplo n.º 8
0
def randomKey(number):
    numPrintable = len(printable.strip())
    key = ':'
    for i in range(number - 1):
        key = key + printable[randint(0, numPrintable) - 1]
    return key
Ejemplo n.º 9
0
from string import printable
import random

digit = printable.strip()
passw = []
lenght = input("Password Lenght ")


def passwords(lenght):
    if lenght == '':
        print("no password is of 0 words")
        exit()
    elif lenght.replace(' ', '').isalpha() == True:
        print("type a number")
        exit()
    else:
        for _ in range(int(lenght)):
            passw.append(random.choice(digit))
    word = ''.join(passw)
    print(word)


passwords(lenght)
Ejemplo n.º 10
0
def main(stdscr):

    curses.curs_set(0)
    curses.init_pair(9, FG, BG)
    stdscr.bkgd(curses.color_pair(9))
    curses.start_color()
    size = stdscr.getmaxyx()

    # background is a matrix of the actual letters (not lit up) -- the underlay.
    # foreground is a binary matrix representing the position of lit letters -- the overlay.
    # dispense is where new 'streams' of lit letters appear from.
    background = rand_string(printable.strip(), size[0] * size[1])
    foreground = []
    dispense = []

    delta = 0
    bg_refresh_counter = random.randint(3, 7)
    lt = time.time()

    while 1:

        if CLEAR:
            stdscr.clear()
        else:
            stdscr.erase()

        now = time.time()
        delta += (now - lt) * UPDATES_PER_SECOND
        lt = now

        while delta >= 1:

            if stdscr.getmaxyx() != size:
                # In the event that the size of the screen has changed,
                # return from this function, effectively restarting
                # pmatrix.
                return

            for _ in range(LETTERS_PER_UPDATE):
                dispense.append(random.randint(0, size[1] - 1))

            for i, c in enumerate(dispense):
                foreground.append([0, c])
                if not random.randint(0, PROBABILITY):
                    del dispense[i]

            for a, b in enumerate(foreground):
                if b[0] < size[0] - 1:
                    stdscr.addstr(b[0], b[1],
                                  background[b[0] * size[0] + b[1]],
                                  curses.color_pair(9))
                    b[0] += 1
                else:
                    # We cannot simply use `del b`. This is because using del
                    # on the local variable b will only remove its binding
                    # from the local namespace. We have to remove it directly
                    # from the list.
                    del foreground[a]

            bg_refresh_counter -= 1
            if bg_refresh_counter <= 0:
                background = rand_string(printable.strip(), size[0] * size[1])
                bg_refresh_counter = random.randint(3, 7)

            delta -= 1
            stdscr.refresh()
Ejemplo n.º 11
0
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable

# Fore, Back and Style are convenience classes for the constant ANSI strings that set 
#     the foreground, background and style. The don't have any magic of their own.
FORES = [ Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE ]
BACKS = [ Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA, Back.CYAN, Back.WHITE ]
STYLES = [ Style.DIM, Style.NORMAL, Style.BRIGHT ]

# This assumes your terminal is 80x24. Ansi minimum coordinate is (1,1).
MINY, MAXY = 1, 24
MINX, MAXX = 1, 80

# set of printable ASCII characters, including a space.
CHARS = ' ' + printable.strip()

PASSES = 1000

def main():
    colorama.init()
    # gratuitous use of lambda.
    pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
    # draw a white border.
    print(Back.WHITE, end='')
    print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
    for y in range(MINY, 1+MAXY):
        print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
    print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='')
    # draw some blinky lights for a while.
    for i in range(PASSES):
Ejemplo n.º 12
0
from ast import literal_eval
from base64 import b64encode
from hashlib import sha1
from itertools import product
from string import printable
import pwn

import schnorr3

printable = printable.strip()

DEBUG = False
if DEBUG:
    p = pwn.remote("localhost", 20014)
else:
    p = pwn.remote("tcp.realworldctf.com", 20014)
pwn.context.log_level = "debug"


def PoW(proof, length):
    assert len(proof) < length
    for work in product(printable, repeat=5):
        work = proof + "".join(work).encode()
        h = sha1(work).hexdigest()
        if h.endswith("0000"):
            break
    return work


def menu(pubkey, choice):
    p.recvuntil("Please tell us your public key:")
Ejemplo n.º 13
0
def main(stdscr):

    curses.curs_set(0)
    curses.init_pair(9, FG, BG)
    stdscr.bkgd(curses.color_pair(9))
    curses.start_color()
    size = stdscr.getmaxyx()

    # background is a matrix of the actual letters (not lit up) -- the underlay.
    # foreground is a binary matrix representing the position of lit letters -- the overlay.
    # dispense is where new 'streams' of lit letters appear from.
    background = rand_string(printable.strip(), size[0] * size[1])
    foreground = []
    dispense   = []

    delta = 0
    bg_refresh_counter = random.randint(3, 7)
    lt = time.time()

    while 1:

        if CLEAR:
            stdscr.clear()
        else:
            stdscr.erase()

        now = time.time()
        delta += (now - lt) * UPDATES_PER_SECOND
        lt = now

        while delta >= 1:

            if stdscr.getmaxyx() != size:
                # In the event that the size of the screen has changed,
                # return from this function, effectively restarting
                # pmatrix.  
                return

            for _ in range(LETTERS_PER_UPDATE):
                dispense.append(random.randint(0, size[1] - 1))

            for i, c in enumerate(dispense):
                foreground.append([0, c])
                if not random.randint(0, PROBABILITY):
                    del dispense[i]

            for a, b in enumerate(foreground):
                if b[0] < size[0] - 1:
                    stdscr.addstr(b[0], b[1],
                                    background[b[0] * size[0] + b[1]],
                                    curses.color_pair(9))
                    b[0] += 1
                else:
                    # We cannot simply use `del b`. This is because using del
                    # on the local variable b will only remove its binding
                    # from the local namespace. We have to remove it directly
                    # from the list.  
                    del foreground[a]

            bg_refresh_counter -= 1
            if bg_refresh_counter <= 0:
                background = rand_string(printable.strip(), size[0] * size[1])
                bg_refresh_counter = random.randint(3, 7)

            delta -= 1
            stdscr.refresh()
Ejemplo n.º 14
0
'''Basic classes for creating a pygame application'''

import pygame, math, sys
from string import printable as _printable
from typing import Type, TypeVar, Optional
from glob import glob
from pygame.locals import *
from recordclass import RecordClass

printable = _printable.strip() + ' '

T = TypeVar('T', bound='ManyOf')

class ManyOf:
    '''
    A class that can be used to group objects and call them at the same time
    reads methods from a given class and creates those methods in this class
    by looping over each provided object and calling that method on it
    '''
    def __init__(self, cls: Type[T], *obj_list: tuple[T]):
        '''
        initialize the ManyOf class
        :cls: the type or class of the objects in obj_list
        :obj_list: the list of objects that the methods will be called on
        '''
        if len(obj_list) < 1:
            raise ValueError('Must pass at least one object in obj_list')
        self.obj_list = obj_list
        for method in filter(lambda x: x != '__class__', dir(cls)):
            if not callable(getattr(cls, method)): # if the method is not a function
                continue # move on to the next method
Ejemplo n.º 15
0
from string import printable

from django.core import validators
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _

PRINTABLE_CHARS = set(printable.strip() + " ")


def printable_name(value: str) -> None:
    """Ensure that team names are printable."""
    if not set(value) <= PRINTABLE_CHARS:
        raise ValidationError(
            _('%(value)s contains non-printable characters.'),
            params={'value': value},
        )


@deconstructible
class NameValidator(validators.RegexValidator):
    regex = r"^[\w.+ -]+\Z"
    message = _("Enter a valid name. This value may contain only letters, "
                "numbers, spaces, and ./+/-/_ characters.")
    flags = 0


@deconstructible
class LenientNameValidator(validators.RegexValidator):
    regex = r"^[]+\Z"
    message = _("Enter a valid name. This value may contain only letters, "
Ejemplo n.º 16
0
def make_pass(pool='chars',
              min_entropy=20,
              min_length=8,
              max_length=30,
              filter_fn=None,
              mod_fn=None,
              join_str='',
              verbose=False,
              **kwargs):

    option_names = ['word_file']

    for arg_name in list(kwargs.keys()):
        if arg_name not in option_names:
            print('Warning: option', arg_name, 'not known.')

    if min_length > max_length:
        raise Exception('min_length must be <= max_length.')

    # error checking
    if pool != 'words' and 'word_file' in kwargs:
        print(
            'Warning: word file supplied but pool not set to words. Ignoring file...',
            file=stderr)

    # figure out what pool we are using
    if pool == 'chars':
        pool = printable.strip()
    elif pool == 'lowercase':
        pool = ascii_lowercase
    elif pool == 'alphanumeric':
        pool = ascii_letters + digits

    elif pool == 'words':

        if 'word_file' not in kwargs:
            word_file = '/usr/share/dict/words'
        else:
            word_file = kwargs['word_file']

        if not isfile(word_file):
            raise Exception('File \'' + word_file + '\' does not exist.')

        f = open(word_file)
        pool = [word.strip() for word in f.readlines()]

        # set the modification to capitalize first letter of each
        if mod_fn is None:
            mod_fn = lambda x: x[0].upper() + x[1:].lower()

    elif type(pool) != list:
        raise Exception("Pool must be a list, 'chars', or 'words'.")

    # get rid of the empty string, obviously
    pool = [x for x in pool if x != '']

    # use a set to remove duplicates. also it's a more appropriate data structure
    pool = set(pool)

    if len(pool) == 0:
        raise Exception("Pool is the empty set!")

    # filter by the given function
    if filter_fn:
        pool = {x for x in pool if filter_fn(x)}
        if len(pool) == 0:
            raise Exception("Filter returned False for every element of pool.")

    # modify pool using the given function
    if mod_fn:
        pool = set(map(mod_fn, pool))

    entropy_per_element = log(len(pool), 2)

    # figure out the smallest number of elements needed to achieve the minimum requested entropy
    min_elements = int(ceil(min_entropy / entropy_per_element))

    # we want a length distribution that stays under max_length but still achieves the entropy needed.
    # so we drop really long words from the pool, so that the average word length is correct.
    # this only matters if the strings in pool are multiple characters
    if any([len(x) > 1 for x in pool]):

        # figure out distribution of lengths
        len_dist = [0] * (max([len(x) for x in pool]))
        for x in pool:
            len_dist[len(x) - 1] += 1

        for n, freq in enumerate(len_dist):
            element_length = n + 1  # zero indexed...
            average_length = sum(
                ((np + 1) * freqp
                 for np, freqp in enumerate(len_dist[:n + 1]))) / sum(
                     (x + 1 for x in len_dist[:n + 1]))
            entropy_per_element = log(sum((x + 1 for x in len_dist[:n + 1])),
                                      2)
            if float(max_length
                     ) / average_length * entropy_per_element < min_entropy:
                if sum((x + 1 for x in len_dist[:n]
                        )) == 0:  # started below the min_entropy :(
                    raise max_len_exception(max_length, min_length,
                                            min_entropy)
                break

        max_element_size = n

        # now generate the final pool we want.
        # it is everything with length less than or equal to element_size (which is now the max value we would want)
        # could also add some from the last group with length equal to element_size? need to calculate n_last
        pool = {
            x
            for x in pool if len(x) < max_element_size + 1
        }  # | set( sample([x for x in pool if len(x) == max_element_size+1], n_last))

        # recalculate these values
        entropy_per_element = log(sum((x + 1 for x in len_dist[:n])), 2)
        min_elements = int(ceil(min_entropy / entropy_per_element))

    # make sure it is at least possible to achieve the entropy we want, while keeping it under max_length
    if min_elements * min([len(x) for x in pool]) > max_length:
        raise max_len_exception(max_length, min_length, min_entropy)

    # need to switch back to a list for the random module
    pool = list(pool)

    # no reason to limit entropy by not allowing repeats, so use choice instead of sample
    element_lst = [choice(pool) for i in range(min_elements)]

    # we might get unlucky and have it too long. keep trying until we don't
    # this reduces the entropy a small bit, since we are rejecting some possibilities.
    # but calculating the true entropy is annoying so... sorry
    while len(join_str.join(element_lst)) > max_length:
        print(
            'Redoing... too long. Entropy slightly less than advertised.\nMaybe try increasing max_length, or using a word list with shorter words.'
        )
        element_lst = [choice(pool) for i in range(min_elements)]

    # if we are below min_length still, add elements until we get there
    while len(join_str.join(element_lst)) < min_length:
        element_lst += [choice(pool)]

    if verbose:
        print('Password: '******'\n')
        if any([len(x) > 1 for x in pool]):
            print(
                'Average word length: ', '{:.2f}'.format(
                    float(sum([len(x) for x in pool])) / len(pool)))
        print('Bits entropy: ',
              '{:.2f}'.format(entropy_per_element * len(element_lst)))
        print('Length: ', len(join_str.join(element_lst)))
        print('N. elements: ', len(element_lst))

    return join_str.join(element_lst)