def perform(request_list): body = { 'clientid': 'TAOBAO', 'verifycode': r'30ad8nUZXX/eWN4Gos29WKSxIYHC9yB/bdb8Dp+zCilxYFylv++PdFjSUi5MUYGA', 'clienttype': 2 } # TODO:AES code calculated assertion = request_list[2] req_url = request_list[0] req_body = body req_body.update(request_list[1]) url_dic = form_dic(info_list, r'/info/') url_dic.update(form_dic(user_list, r'/user/')) url_dic.update(form_dic(trade_list, r'/trade/')) url_dic.update(form_dic(pay_list, r'/trade/')) if req_url not in url_dic: return False try: response = getresponse(geturl(url_dic[req_url] + req_url, req_body), assertion) if isinstance(response, dict): response = response.items() try: update_dic_data(req_url, response) except WrongData: print "Update job fails while url is %r" % req_url if response != [] and req_url != 'cinemahallsections': print random.choice(response) if req_url == 'cinemahallsections': print response return True except UrlError: return False
def generate_password(length, options=[]): """ Generate a new password of given length using specified options. Options is a string array possibly containing containing ['Uppercase', 'Numbers', 'Symbols']. """ lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase numbers = string.digits symbols = '!@#$%^&*?' password = list() for i in range(length): password.append(random.choice(lowercase)) if 'Uppercase' in options: num_to_replace = int(length/5) + 1 for i in range(num_to_replace): replace_idx = random.randint(0, length-1) password[replace_idx] = random.choice(uppercase) if 'Numbers' in options: num_to_replace = int(length/5) + 1 for i in range(num_to_replace): replace_idx = random.randint(0, length-1) password[replace_idx] = random.choice(numbers) if 'Symbols' in options: num_to_replace = int(length/6) + 1 for i in range(num_to_replace): replace_idx = random.randint(0, length-1) password[replace_idx] = random.choice(symbols) return ''.join(password)
def generate_request(**request_parameters): '''Generate a token provisioning request.''' default_model = 'MacBookPro%d,%d' % (random.randint(1, 12), random.randint(1, 4)) default_request_parameters = { 'timestamp':int(time.time()), 'token_model':'VSST', 'otp_algorithm':'HMAC-SHA1-TRUNC-6DIGITS', 'shared_secret_delivery_method':'HTTPS', 'manufacturer':'Apple Inc.', 'serial':''.join(random.choice(string.digits + string.ascii_uppercase) for x in range(12)), 'model':default_model, 'app_handle':'iMac010200', 'client_id_type':'BOARDID', 'client_id':'Mac-' + ''.join(random.choice('0123456789ABCDEF') for x in range(16)), 'dist_channel':'Symantec', 'platform':'iMac', 'os':default_model, } default_request_parameters.update(request_parameters) request_parameters = default_request_parameters data_before_hmac = u'%(timestamp)d%(timestamp)d%(client_id_type)s%(client_id)s%(dist_channel)s' % request_parameters request_parameters['data'] = base64.b64encode( hmac.new( HMAC_KEY, data_before_hmac.encode('utf-8'), hashlib.sha256 ).digest() ).decode('utf-8') return REQUEST_TEMPLATE % request_parameters
def crypt(SHELL, brutelen=7, alphanum=False): nums = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' if alphanum: keyspace = nums + alpha + alpha.upper() else: keyspace = nums BLOCK_SIZE = 16 BRUTE_LENGTH = brutelen PADDING = '\x00' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) #DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) decoded = '' secret = Random.new().read(BLOCK_SIZE-BRUTE_LENGTH) secret += ''.join(random.choice(keyspace) for i in range(BRUTE_LENGTH)) #print secret IV = Random.new().read(16) checkstring = ''.join(random.choice(nums+alpha) for i in range(BLOCK_SIZE)) cipher = AES.new(secret) encoded = EncodeAES(cipher, SHELL) control = cipher.encrypt(checkstring) encoded += secret[:-BRUTE_LENGTH] + control + checkstring encoded = base64.b64encode(encoded) return encoded
def carGen(): global CAR_LIST, USER_TEL alpha = list( '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-~') CAR_TPYE = [ 'Porsche', 'Lamborghini', 'Maybach', '大众', 'bmw', 'Bentley', 'Rolls-Royce', 'mercedes-benz' ] picture = ''.join( random.choice(alpha) for i in range(random.randint(3, 7))) isDetail = random.randint(0, 1) if isDetail: detailImage1 = ''.join( random.choice(alpha) for i in range(random.randint(3, 7))) car_type = random.choice(CAR_TPYE) owner_id = random.randint(1, len(USER_LIST)) owner_tel = USER_TEL[owner_id - 1] price = random.randint(10000, 1000000000) transfer_time = 0 isSold = False isAssess = False isCheck = False if isDetail: return 'INSERT INTO `CAR_TABLE` (`PICTURE`, `DETAIL_IMAGE1`, `CAR_TYPE`, `OWNER_ID`, `OWNER_TEL`, `PRICE`, `TRANSFER_TIME`, `IS_SOLD`, `IS_ASSESS`, `IS_CHECK`) VALUES (\'' + picture + '\', \'' + detailImage1 + '\', \'' + car_type + '\', ' + str( owner_id) + ', \'' + owner_tel + '\', ' + str(price) + ', ' + str( transfer_time) + ', ' + str(isSold) + ', ' + str( isAssess) + ', ' + str(isCheck) + ');\n' else: return 'INSERT INTO `CAR_TABLE` (`PICTURE`, `CAR_TYPE`, `OWNER_ID`, `OWNER_TEL`, `PRICE`, `TRANSFER_TIME`, `IS_SOLD`, `IS_ASSESS`, `IS_CHECK`) VALUES (\'' + picture + '\', \'' + car_type + '\', ' + str( owner_id) + ', \'' + owner_tel + '\', ' + str(price) + ', ' + str( transfer_time) + ', ' + str(isSold) + ', ' + str( isAssess) + ', ' + str(isCheck) + ');\n'
def adminGen(): global ADMIN_LIST alpha = list( '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-~') username_length = random.randint(3, 10) username = ''.join([random.choice(alpha) for i in range(username_length)]) password = '******' salt = hex(random.getrandbits(160))[2:] password_hash = SHA256.new( (password + SALT_PREFIX + salt).encode('utf-8')).hexdigest() phone = '1' + ''.join([str(random.randint(0, 9)) for i in range(10)]) hasId = random.randint(0, 1) identity_number = '' realname = '' email = ''.join( [random.choice(alpha) for i in range(random.randint(7, 15))]) + '@buaa.edu.cn' ADMIN_LIST.append(username) if hasId: identity_number = ''.join( [str(random.randint(0, 9)) for i in range(17)]) + random.choice(list('0123456789X')) realname = ''.join([random.choice(alpha) for i in range(4)]) identity_number = SHA256.new( identity_number.encode('utf-8')).hexdigest() data = username + password_hash + salt + phone + realname + identity_number mac = SHA256.new(data.encode('utf-8')).hexdigest() if hasId: return 'INSERT INTO `ADMIN_TABLE` (`NAME`, `PASSWORD`, `SALT`, `PHONE`, `IDENTITY_NUMBER`, `REAL_NAME`, `EMAIL`, `MAC`) VALUES (\'' + username + '\', \'' + password_hash + '\', \'' + salt + '\', \'' + phone + '\', \'' + identity_number + '\', \'' + realname + '\', \'' + email + '\', \'' + mac + '\');\n' else: return 'INSERT INTO `ADMIN_TABLE` (`NAME`, `PASSWORD`, `SALT`, `PHONE`, `EMAIL`, `MAC`) VALUES (\'' + username + '\', \'' + password_hash + '\', \'' + salt + '\', \'' + phone + '\', \'' + email + '\', \'' + mac + '\');\n'
def __init__(self): super(Xeger, self).__init__() self._cache = dict() self._categories = { "category_digit": lambda: self._alphabets['digits'], "category_not_digit": lambda: self._alphabets['nondigits'], "category_space": lambda: self._alphabets['whitespace'], "category_not_space": lambda: self._alphabets['nonwhitespace'], "category_word": lambda: self._alphabets['word'], "category_not_word": lambda: self._alphabets['nonword'], } self._cases = {"literal": lambda x: unichr(x), "not_literal": lambda x: choice( string.printable.replace(unichr(x), '')), "at": lambda x: '', "in": lambda x: self._handle_in(x), "any": lambda x: self.printable(1), "range": lambda x: [unichr(i) for i in xrange(x[0], x[1]+1)], "category": lambda x: self._categories[x](), 'branch': lambda x: ''.join(self._handle_state(i) for i in choice(x[1])), "subpattern": lambda x: self._handle_group(x), "assert": lambda x: ''.join(self._handle_state(i) for i in x[1]), "assert_not": lambda x: '', "groupref": lambda x: self._cache[x], 'max_repeat': lambda x: self._handle_repeat(*x), 'negate': lambda x: [False], }
def generate_password(length=16, symbolgroups=DEFAULT_PASSWORD_SYMBOLS): """Generate a random password from the supplied symbol groups. At least one symbol from each group will be included. Unpredictable results if length is less than the number of symbol groups. Believed to be reasonably secure (with a reasonable password length!) """ # NOTE(jerdfelt): Some password policies require at least one character # from each group of symbols, so start off with one random character # from each symbol group password = [random.choice(s) for s in symbolgroups] # If length < len(symbolgroups), the leading characters will only # be from the first length groups. Try our best to not be predictable # by shuffling and then truncating. random.shuffle(password) password = password[:length] length -= len(password) # then fill with random characters from all symbol groups symbols = ''.join(symbolgroups) password.extend([random.choice(symbols) for _i in range(length)]) # finally shuffle to ensure first x characters aren't from a # predictable group random.shuffle(password) return ''.join(password)
def setup(self, security): # Pick p, q primes such that p | q - 1, that is equvalent to # say that q = r*p + 1 for some r p = number.getPrime(security, Random.new().read) print("p = ",p) r = 1 while True: q = r*p + 1 if number.isPrime(q): print("q = ",q) break r += 1 # Compute elements of G = {i^r mod q | i in Z_q*} G = [] for i in range(1, q): # Z_q* G.append(i**r % q) G = list(set(G)) print("Order of G = {i^r mod q | i in Z_q*} is " + str(len(G)) + " (must be equal to p).") # Since the order of G is prime, any element of G except 1 is a generator g = random.choice(list(filter(lambda e: e != 1, G))) print("g = ",g) h = random.choice(list(filter(lambda e: e != 1 and e != g, G))) print("h = ",h) # g and h are elements of G such that nobody knows math.log(h, g) (log of h base g) return q,g,h
def symmetricKey(self, bits): bits = int(bits) if bits == 128: key = bytes(''.join(random.choice(ascii_lowercase) for i in range(16))) if bits == 256: key = bytes(''.join(random.choice(ascii_lowercase) for i in range(32))) return key
def _handle_in(self, value): candidates = list(chain(*(self._handle_state(i) for i in value))) if candidates[0] is False: candidates = set(string.printable).difference(candidates[1:]) return choice(list(candidates)) else: return choice(candidates)
def random_plugin_gus(): length = 10 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u'p_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u'p_'+(''.join(random.choice('0123456789') for x in range(length)))
def encryption_oracle(data): prepad = Random.get_random_bytes(random.choice(range(5, 11))) postpad = Random.get_random_bytes(random.choice(range(5, 11))) padded = pkcs7_pad(prepad + data + postpad) key = keygen() if random.choice(range(2)) == 0: iv = keygen() return cbc_encrypt(data, key, iv) else: return ecb_encrypt(data, key)
def encryption_oracle(cleartext, key): choice = random.choice([AES_ECB_MODE, AES_CBC_MODE]) if choice == AES_ECB_MODE: func = lambda x: aes_ecb_encrypt(x, key) else: IV = Random.new().read(16) func = lambda x: aes_cbc_encrypt(x, key, IV) return func( paddpkcs7( Random.new().read(random.choice(range(5, 11))) + cleartext + Random.new().read(random.choice(range(5, 11))), 16)), choice
def random_submission_gus(testingmode=False): """ this need to be not guessable because this secret auth the WB during the submission procedure. """ length = 50 if testingmode: return u's_'+(''.join(random.choice('A') for x in range(length))) else: return u's_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def generate_password(range=None, size=16): if not range: range = string.digits + string.ascii_letters + string.digits a = [] while len(a) < size - 4: a.append(random.choice(range)) while len(a) < size - 2: a.append(random.choice(r"+=-@#~,.[]()!%^*$")) random.shuffle(a) return random.choice(string.ascii_letters) + \ ''.join(a) + \ random.choice(string.ascii_letters)
def test_ch22(self): import time time.sleep(random.choice(range(1, 10))) time_now = int(time.time()) orig_seed = time_now obj = MT19937(time_now) num = obj.extract_number() time.sleep(random.choice(range(1, 10))) i = break_mt19937_seeded_time(int(time.time()), num) self.assertEqual(i, orig_seed)
def random_tip_gus(): """ need to be NOT guessable """ length = 50 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u't_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u't_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def random_file_gus(): """ need to be random XXX file is now starting with f_ and is supposed to be random """ length = 30 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u'f_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u'f_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def random_submission_gus(): """ this need to be not guessable because this secret auth the WB during the submission procedure. """ length = 50 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u's_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u's_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def random_receiver_gus(): """ maybe guessable, because is an information available to the whistleblower, and then every time is used as input, need to be checked in coherence, in the context. anyway we made it not guessable, just to avoid enumeration. """ length = 20 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u'r_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u'r_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def chooseAxes(numBits): """Return Alice and Bob's randomly chosen mstment axes for the specified number of qubits in the E91 protocol: A chooses from (0, pi/4, pi/2) with equal probability, B chooses from (pi/4, pi/2, 3pi/4) with equal probability. """ choicesA = [0, pi / 8, pi / 4] choicesB = [0, pi / 8, -pi / 8] basesA = [] basesB = [] for j in range(numBits): basesA.append(random.choice(choicesA)) basesB.append(random.choice(choicesB)) return (basesA, basesB)
def generate_random_password(self, size=10 ): """ Generates random password of given size it ensures - 1 uppercase 1 lowercase 1 digit 1 punc """ P = [random.choice(s) for s in self.must_set] P.extend([random.choice(self.All) for n in range(size-len(self.must_set))]) n = random.randint(0, MAX_INT) password = self.decode2string(n, P) return password
def reset(self): self.surface.fill(backgroundcolor) self.point = 0 self.level = 1 self.count = 0 self.time = 500 self.board_show = {i : [SingleBlock(self.surface, BLACK, WHITE) for j in range(NROWS)] for i in range(NCOLS)} self.board = {i: [0 for j in range(NROWS + 1)] for i in range(-1, NCOLS + 1)} self.board[-1] = [1 for j in range(NROWS + 1)] self.board[NCOLS] = [1 for j in range(NROWS + 1)] for i in range(-1, NCOLS + 1): self.board[i][NROWS] = 1 self.block = Block(self.board, self.board_show, random.choice(Blocks)) self.block_next = random.choice(Blocks) self.draw()
def random_context_gus(): """ need to be random (because not all context maybe reachable directly from the home page, or not all context need to be disclosed publicly), but need to be short, just for do not create a loooong URL """ length = 20 if TESTING: global global_debug_counter global_debug_counter += 1 string_value = str(global_debug_counter) return u'c_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value else: return u'c_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def post_request(self, method, filename, request_params={}): """ Generate an API POST request string for an image upload search. The POST request string can be sent as is to issue the POST request to the API server. - `method`, API method being called. - `filename`, the filename of the image that is being searched for. - `request_params`, the list of search parameters. Returns: - `request_url`, the URL to send the search to. - `boundary`, the boundary to be used in the POST request. """ if filename is None or not len(str(filename).strip()): raise APIRequestError("Must specify an image to search for.") # Have to generate a boundary, nonce, and date to use in generating a POST # request signature boundary = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) nonce = self._generate_nonce() date = int(time.time()) api_signature = self._generate_post_hmac_signature( "search", boundary, nonce, date, filename, request_params=request_params) return self._request_url(method, nonce, date, api_signature, request_params), boundary
def prepare_request(self,url,token=None,secret='',additional_params={},method='GET'): encode=lambda t:urlquote(str(t),'') urlquh=lambda t:urlquote(str(t),'~') params={'oauth_consumer_key':self.consumer_key, 'oauth_signature_method':'HMAC-SHA1', 'oauth_timestamp':str(int(time())), 'oauth_nonce':''.join(list(choice(seqstr) for i in xrange(64))), 'oauth_version':'1.0'} if token: params['oauth_token']=token elif self.callback_url: params['oauth_callback']=self.callback_url params.update(additional_params) for k,v in params.iteritems(): if isinstance(v,unicode): params[k]=v.encode('utf8') params_str='&'.join([encode(k)+'='+urlquh(v) for k,v in sorted(params.iteritems())]) params['oauth_signature']=hmac('&'.join([self.consumer_secret,secret]), '&'.join([method,encode(url),urlquh(params_str)]), sha1).digest().encode('base64').strip() return '&'.join([urlquote_plus(str(k),'~')+'='+urlquote_plus(str(v),'~') for k,v in sorted(params.iteritems())])
def random_file_gus(): """ need to be random XXX file is now starting with f_ and is supposed to be random """ length = 30 return u'f_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def ranpassgen(self, passlen, lower, upper, spec, dig): """ Constructs a random password using the provided parameters. :param passlen: the length of the password to be generated :param lower: use lower case characters in the password :param upper: use upper case characters in the password :param spec: use special characters in the password :param dig: use digits in the password :return: Returns randomly generated password """ char_set = [] if lower is True: char_set.append(self.ascii_lower) if upper is True: char_set.append(self.ascii_upper) if spec is True: char_set.append(self.special) if dig is True: char_set.append(self.digits) characters = "".join(char_set[:4]) password = "".join(random.choice(characters) for i in range(int(passlen))) return password
def ranpassgen(self, passlen, lower, upper, spec, dig): """ Constructs a random password using the provided parameters. :param passlen: the length of the password to be generated :param lower: use lower case characters in the password :param upper: use upper case characters in the password :param spec: use special characters in the password :param dig: use digits in the password :return: Returns randomly generated password """ char_set = [] if lower is True: char_set.append(self.ascii_lower) if upper is True: char_set.append(self.ascii_upper) if spec is True: char_set.append(self.special) if dig is True: char_set.append(self.digits) characters = "".join(char_set[:4]) password = "".join( random.choice(characters) for i in range(int(passlen))) return password
def generate_unused_dbkey(): """ Returns a id matching /[A-Z]{2}[1-9][0-9]{3}/ for example WL2007 """ # Two upper case letters new_key = "".join(random.choice(settings.CHARS) for x in range(2)) # Four digit number, not starting with zero new_key += str(random.choice(settings.NUMBERS[1:10])) new_key += "".join(random.choice(settings.NUMBERS) for x in range(3)) try: Profile.objects.get(uid = new_key) # If we get to here, the key already exists. generate another one.. return generate_unused_dbkey() except ObjectDoesNotExist: return new_key
def random_str(length=8): '''生成可打印的 [0-9a-zA-Z] 随机字符串.''' seeds = string.letters + string.digits random_str = '' for x in xrange(length): random_str += random.choice(seeds) return random_str
def encrypt(): try: global shellcode global iv global keyList key = random.choice(keyList) #Let's get our shellcode up to 32 bytes (has to be multiple of 16) shellPad = 32 - len(shellcode) shellPadBytes = b'\xff' * shellPad shellcode = shellPadBytes + shellcode #This is where we do our actual encryption! aes = AES.new(key, AES.MODE_CBC, iv) data = shellcode encd = aes.encrypt(data) #Let's get it into printable format! output = "" for x in bytearray(encd): output += "\\x" output += '%02x' % x output = output.replace("\\x", r'\\x') print("\n[+] Encrypted Shellcode: " + output) except: print "Something went wrong with the encryption process."
def gen_token(): global key iv = rndfile.read(16) crypt = AES.new(key, AES.MODE_CBC, iv) plaintext = random.choice(data) ciphertext = crypt.encrypt(pad_pkcs7(plaintext, 16)) return iv+ciphertext
def generate(wordlist, num_words, num_passwords, min_word_length=4, max_word_length=100, min_length=4, max_length=100): wordlist = [ x for x in wordlist if min_word_length <= len(x) <= max_word_length ] generated_passwords = 0 bad_passwords = 0 while generated_passwords < num_passwords: words = [random.choice(wordlist) for unused_j in range(num_words)] password = ''.join(words) if not (min_length <= len(password) <= max_length): bad_passwords += 1 if bad_passwords >= 1000: raise Exception( "generated too many passwords not fitting the length requirements, bailing out" ) continue yield password, tuple(words) generated_passwords += 1
def measureEntangledState(basisA, basisB, errorRate=0.0): """Return Alice and Bob's measurement results on a pair of maximally entangled qubits. basis[A,B] contain Alice and Bob's axes of mstment. """ # Alice measures either basis state with equal probability # -1 will correspond to False (0) and +1 will correspond to True (1) resultA = random.choice([-1, 1]) # If Alice and Bob chose the same axis of mstment, Bob's result is # perfectly anti-correlated with Alice's. Otherwise its correlation # coefficient is given by -cos[2(basisA-basisB)]. We use the result # r to generate a correlated random number that gives Bob's result. r = -1 * cos(2 * (basisA - basisB)) r2 = r**2 ve = 1 - r2 SD = sqrt(ve) e = np.random.normal(0, SD) resultB = resultA * r + e resultA = False if resultA < 0 else True resultB = False if resultB < 0 else True if errorRate: samples = np.random.rand(2) if samples[0] < errorRate: resultA = not (resultA) if samples[1] < errorRate: resultB = not (resultB) return (resultA, resultB)
def generate_expiring_request(lifetime, plaintext): """ Generate the parameters needed for an expiring email request with the given payload. Payload should be comma-delimited, and the consumer should expect to find and verify a timestamp and nonce appended to the given plaintext. """ # Add nonce rng = Random.new() nonce = ''.join(choice(string.ascii_uppercase + string.digits) for _ in range(256)) expiry = str(time.time() + lifetime) plaintext = (plaintext + "," + expiry + "," + nonce).encode('utf-8') # Pad the plaintext to the next full block with commas, because I can't be arsed to # write an actually clever parser. bs = Blowfish.block_size paddinglen = bs - (len(plaintext) % bs) plaintext += b',' * paddinglen # Generate random IV of size one block. iv = rng.read(bs) cipher = Blowfish.new(VERIFICATION_SECRET_KEY, Blowfish.MODE_CBC, iv) ciphertext = cipher.encrypt(plaintext) # Generate the verification hash. verification = hashlib.sha256() verification.update(plaintext + VERIFICATION_HASH_SECRET.encode('utf-8')) verify_hex = verification.hexdigest() return base64.urlsafe_b64encode(iv), base64.urlsafe_b64encode(ciphertext), verify_hex
def generate_password(keyfile, args): characters = args.get('characters', keyfile.characters) length = int(args.get('length', keyfile.length)) password = '' while len(password) < length: password += random.choice(characters) return password
def generate_expiring_request(lifetime, plaintext): """ Generate the parameters needed for an expiring email request with the given payload. Payload should be comma-delimited, and the consumer should expect to find and verify a timestamp and nonce appended to the given plaintext. """ # Add nonce rng = Random.new() nonce = ''.join( choice(string.ascii_uppercase + string.digits) for _ in range(256)) expiry = str(time.time() + lifetime) plaintext = (plaintext + "," + expiry + "," + nonce).encode('utf-8') # Pad the plaintext to the next full block with commas, because I can't be arsed to # write an actually clever parser. bs = Blowfish.block_size paddinglen = bs - (len(plaintext) % bs) plaintext += b',' * paddinglen # Generate random IV of size one block. iv = rng.read(bs) cipher = Blowfish.new(VERIFICATION_SECRET_KEY, Blowfish.MODE_CBC, iv) ciphertext = cipher.encrypt(plaintext) # Generate the verification hash. verification = hashlib.sha256() verification.update(plaintext + VERIFICATION_HASH_SECRET.encode('utf-8')) verify_hex = verification.hexdigest() return base64.urlsafe_b64encode(iv), base64.urlsafe_b64encode( ciphertext), verify_hex
def get_db_prep_value(self, value, connection=None, prepared=False): if value is None: return None value = smart_str(value) if not self._is_encrypted(value): padding = self._get_padding(value) if padding > 0: value += "\0" + ''.join([ random.choice(string.printable) for index in range(padding-1) ]) if self.block_type: self.cipher = self.cipher_object.new( self.secret_key, getattr(self.cipher_object, self.block_type), self.iv) if PYTHON3 is True: value = self.prefix + binascii.b2a_hex( self.iv + self.cipher.encrypt(value)).decode('utf-8') else: value = self.prefix + binascii.b2a_hex( self.iv + self.cipher.encrypt(value)) else: if PYTHON3 is True: print('>>>', value, '-->', len(value)/16) value = self.prefix + binascii.b2a_hex( self.cipher.encrypt(value)).decode('utf-8') else: value = self.prefix + binascii.b2a_hex( self.cipher.encrypt(value)) return value
def genKey(self): """Randomly generate a private key""" key = "" H = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for i in range(16): key += random.choice(H) return key
def main(): print('16-bit hash.') print('k=8 spacetime tradeoff.', end='\n\n') print('building diamond...') diamond = build_diamond() # diamond = testvector5() print('\n') print(diamond) ##### MAKE FORECAST ##### for key in diamond[-1]: hashdrop = f(diamond[-1][key], key) print('\nh_diamond hashdrop:', hashdrop) forecast = choice(open('/usr/share/dict/words', 'r').read().splitlines()).encode() forepad = forecast + b' #' + (b'\x00' * (32 - 2 - len(forecast))) print('\n\n', forepad) h2 = f(forepad) print('finding link message') m_link = find_m_link(h2, diamond[0]) print('m_link:', m_link) prediction = b'' prediction += forepad + m_link for block in diamond: prediction += block[f(prediction)] print('\npostseason message:', prediction, '\n\nhash:', f(prediction)) if f(prediction) == hashdrop: print('huzzah') else: print('kaboom')
def generate_random_password(): """Utility method to generate a random password. return (str): a random string. """ return "".join((random.choice('abcdefghjkmnpqrstuvwxyz23456789') for _ in range(10)))
def generate_token(length=32): """ Generates a random token containing a-z A-Z 0-9 of size `length` Crypto.Random may be a bad choice, consider switching to os.urandom: http://stackoverflow.com/a/20469525/263132 """ return ''.join(chr(random.choice(_POOL)) for _ in range(length))
def login(request, *args, **kwargs): response = authlogin(request, *args, **kwargs) if request.user.is_authenticated(): lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(30)] key = "".join(lst) request.user.db.magic_cookie = key return response
def generate_fake_generations(): genesis_account = Account.objects.get(address=GENESIS_ADDRESS) num_transactions = random.randint(1, MAX_TX_PER_BLOCK) with open("genesisprivatekey.pem", "r") as f: key = RSA.import_key(f.read()) transactions = [] print("there are " + str(num_transactions) + "transactions generated in this block") for _ in range(num_transactions): amount = Decimal(str(random.randint(0, 10))) target_address = random.choice(account_addresses) target_account = Account.objects.get(address=target_address) genesis_transactions = Transaction.objects.filter( sender=genesis_account) nonce = len(genesis_transactions) + 1 transaction = Transaction.objects.create(sender=genesis_account, amount=amount, receiver=target_account, nonce=nonce) transaction.transaction_hash = transaction.hash_hex() transaction.signature = pss.new(key).sign( transaction.hash_transaction()) transaction.save() transactions.append(transaction) return transactions
def pad_message(message): """ Adds padding to the front of the message. Padding is generated by random selections from RANDOM_SAMPLE using Crypto.Random.random.choice(). A new message is returned in the following format: "{padding}`{message}" padding is added to the front to obscure common output from the command line i.e. windows sends the stdin to the stdout, beginning with the working directory. """ # determine the pad_length based on the key BLOCK_SIZE if len(message) < BLOCK_SIZE: pad_length = (BLOCK_SIZE - len(message)) elif len(message) > BLOCK_SIZE: pad_length = (len(message) % BLOCK_SIZE) else: pad_length = BLOCK_SIZE if pad_length < 16: pad_length += BLOCK_SIZE # reduce by one for the delimiter that is added between message and padding pad_length -= 1 padding = "" while len(padding) < pad_length: padding += random.choice(RANDOM_SAMPLE) return"{}`{}".format(padding, message)
def test_dlog_eq(iters=1): print "test_dlog_eq:" keys = generate_keys() n = keys['pub'] z = n - 1 p, q = keys['priv'] for i in range(iters): print 'i = ', i r = random.randint(0, int((p - 1) * (q - 1))) y = random.randint(0, int(n - 1)) Y = powmod(y, r, n) Z = powmod(z, r, n) P_dlog = proof_dlog_eq(r, y, n) assert (verify_dlog_eq(n, y, Y, Z, P_dlog)) P_dlog[random.randint(0, len(P_dlog)-1)][random.randint(0,2)] += \ random.choice([-1, 1]) assert (not verify_dlog_eq(n, y, Y, Z, P_dlog)) print "test_dlog_eq pass"
def gen_key(size=16): """ 用Crypto.Random模块生成的真随机字符串 """ _key = '' return _key.join( cry_rand.choice(string.letters + string.digits) for i in range(size))
def get_db_prep_value(self, value, connection=None, prepared=False): if value is None: return None value = smart_bytes(value) if not self._is_encrypted(value): padding = self._get_padding(value) if padding > 0: value += smart_bytes("\0" + ''.join([ random.choice(string.printable) for index in range(padding-1) ])) if self.block_type: self.cipher = self.cipher_object.new( self.secret_key, getattr(self.cipher_object, self.block_type), self.iv) value = smart_bytes(self.prefix) + binascii.b2a_hex( smart_bytes(self.iv) + self.cipher.encrypt(smart_bytes(value)) ) else: value = smart_bytes(self.prefix) + binascii.b2a_hex( self.cipher.encrypt(smart_bytes(value)) ) return value
def random_folder_gus(): """ need to be random XXX this has been changed to starting d_ for directory. """ length = 20 return u'd_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
def randKey(alpha, keyLen): key = "" count = 0 while count < keyLen: key += random.choice(alpha) count += 1 return key
def redeem_token(claim): try: # verify the checksum of the file against its "token" object token = claim["token"] token_str = json.dumps(token) print("Verifying token...") checksum = bytes.fromhex(claim["checksum"]) validate_checksum(token_str, checksum) print("Validated Checksum.") print("Fetching Keys from Bank") response = requests.get(claim["bank-address"] + "/public-key") data = response.json() e = int.from_bytes(bytes.fromhex(data.get("key")), "big") n = int.from_bytes(bytes.fromhex(data.get("modulus")), "big") print("Validating Bank Signature...") checksum = int.from_bytes(checksum, "big") signature = int.from_bytes(bytes.fromhex(claim.get("signature")), "big") validate_signature(checksum, signature, (e, n)) print("Signature Good.") session_id = str(uuid.uuid4()) print("Establishing Session: %s" % session_id) pattern = list( random.choice([0, 1]) for identity in token["identities"]) print("Requesting keys for from Client: \n" + str(pattern)) _sessions[session_id] = claim, pattern return session_id, pattern except Exception as e: raise e
def home(request): """Renders the home page.""" key = '000102030405060708090A0B0C0D0E0F' nonce = 'BBAA99887766554433221103' associated = '' #if request.GET.get('U'): # message = 'You submitted: %r' % request.GET['U'] #else: # message = 'You submitted nothing' #UID = ''+request.GET.get('U').upper().encode() #TF = binascii.hexlify(request.GET.get('TF').upper()) #TS = ''+request.GET.get('TS') #RLC = request.GET.get('RLC') PT = "%s%s%s%s" % (request.GET.get('U'),binascii.hexlify(request.GET.get('TF').upper()),request.GET.get('TS'),request.GET.get('RLC')) [cipher,tag] = ocb_encrypt(key,nonce,'',PT) assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { #/?U=E0391122334455&TF=AA&TS=0000019B&RLC=D7B9EEA9C9FD689333AD097A9BD79C12B67A0FA6130BBC7890F12AEADF01206CB78F9DDA10A56933AE08F12588 'namee':random.choice(['Dogs', 'Cats', 'Bears']), #'getu':request.GET.get('U'), #'gettf':binascii.hexlify(request.GET.get('TF').upper()), #'getts':request.GET.get('TS'), #'getrlc':request.GET.get('RLC'), 'ocb': [binascii.hexlify(cipher).upper(),binascii.hexlify(tag).upper()], 'decry': ocb_decrypt(key,nonce,associated,cipher,tag), 'title':'Home Page', 'year':datetime.now().year, } )
def generate_random_password(self, length = 8): #concatination of all chosen sets (uppercase, lowercase, etc.) password_set = self.UPPERCASE_LETTERS + self.LOWERCASE_LETTERS + self.DIGITS + self.PUNCTUATION password = '' for i in xrange(length): password += random.choice(password_set) return password