def generate_challenge(context, ekcert, aikpub, secret, ek=None): """ Generate a challenge to verify that the AIK is under the control of the TPM we're talking to. :param context: The TSS context to use :param ekcert: The Endorsement Key certificate :param aikpub: The public Attestation Identity Key blob :param secret: The secret to challenge the TPM with :param ek: TspiKey representing ek. ekcert is ignored if ek is provided. :returns: a tuple containing the asymmetric and symmetric components of the challenge """ aeskey = bytearray(os.urandom(16)) iv = bytearray(os.urandom(16)) if ek is None: # Replace rsaesOaep OID with rsaEncryption ekcert = ekcert.replace('\x2a\x86\x48\x86\xf7\x0d\x01\x01\x07', '\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01') x509 = M2Crypto.X509.load_cert_string(ekcert, M2Crypto.X509.FORMAT_DER) pubkey = x509.get_pubkey() rsakey = pubkey.get_rsa() else: pubkey = ek.get_pubkey() n = m2.bin_to_bn(pubkey) n = m2.bn_to_mpi(n) e = m2.hex_to_bn("010001") e = m2.bn_to_mpi(e) rsakey = M2Crypto.RSA.new_pub_key((e, n)) # TPM_ALG_AES, TPM_ES_SYM_CBC_PKCS5PAD, key length asymplain = bytearray([0x00, 0x00, 0x00, 0x06, 0x00, 0xff, 0x00, 0x10]) asymplain += aeskey m = hashlib.sha1() m.update(aikpub) asymplain += m.digest() # Pad with the TCG varient of OAEP asymplain = tpm_oaep(asymplain, len(rsakey)/8) # Generate the EKpub-encrypted asymmetric buffer containing the aes key asymenc = bytearray(rsakey.public_encrypt(asymplain, M2Crypto.RSA.no_padding)) # And symmetrically encrypt the secret with AES cipher = M2Crypto.EVP.Cipher('aes_128_cbc', aeskey, iv, 1) cipher.update(secret) symenc = cipher.final() symheader = struct.pack('!llhhllll', len(symenc) + len(iv), TPM_ALG_AES, TPM_ES_SYM_CBC_PKCS5PAD, TPM_SS_NONE, 12, 128, len(iv), 0) symenc = symheader + iv + symenc return (asymenc, symenc)
def digest_auth(qop=None, user='******', passwd='passwd'): """Prompts the user for authorization using HTTP Digest auth""" if qop not in ('auth', 'auth-int'): qop = None if 'Authorization' not in request.headers or \ not check_digest_auth(user, passwd) or \ not 'Cookie' in request.headers: response = app.make_response('') response.status_code = 401 # RFC2616 Section4.2: HTTP headers are ASCII. That means # request.remote_addr was originally ASCII, so I should be able to # encode it back to ascii. Also, RFC2617 says about nonces: "The # contents of the nonce are implementation dependent" nonce = H(b''.join([ getattr(request,'remote_addr',u'').encode('ascii'), b':', str(time.time()).encode('ascii'), b':', os.urandom(10) ])) opaque = H(os.urandom(10)) auth = WWWAuthenticate("digest") auth.set_digest('*****@*****.**', nonce, opaque=opaque, qop=('auth', 'auth-int') if qop is None else (qop, )) response.headers['WWW-Authenticate'] = auth.to_header() response.headers['Set-Cookie'] = 'fake=fake_value' return response return jsonify(authenticated=True, user=user)
def test_oaep(): """Run through the OAEP encode/decode for lots of random values.""" from os import urandom p = OAEP(urandom) for k in xrange(45,300): for i in xrange(0,1000): b = i % (k - 2*20 - 3) # message length if b == 0: j = -1 else: j = i % b # byte to corrupt print "test %s:%s (%s bytes, corrupt at %s)" % (k,i,b,j) msg = urandom(b) pmsg = p.encode(k,msg) # Test that padding actually does something assert msg != pmsg, "padded message was just the message" # Test that padding is removed correctly assert p.decode(k,pmsg) == msg, "message was not decoded properly" # Test that corrupted padding gives an error try: if b == 0: raise ValueError newb = urandom(1) while newb == pmsg[j]: newb = urandom(1) pmsg2 = pmsg[:j] + newb + pmsg[j+1:] p.decode(k,pmsg2) except ValueError: pass else: raise AssertionError("corrupted padding was still decoded")
def u_ut_iv(size, tty='L', exc=False): ''' make random iv for aes block @param integer size: type of aes [16,24,32] @param char tty: type of return @param bool exc: flag if ignore limit of string @return list ''' if(tty == 'L'): ivv = [] app = ivv.append for i in range(size): try: app(int.from_bytes(urandom(1), 'little')) except IndexError: app(i) elif(tty == 'S'): ivv = '' if(exc): return urandom(size) else: for i in range(size): try: ivv = '%s%s' % (ivv, int.from_bytes(urandom(1), 'little')) except IndexError: ivv = '%s%s' % (ivv, i) if(len(ivv) > LIMIT): ivv = ivv[0:LIMIT] return ivv
def get_token(request): user_id = authenticated_userid(request) discussion_id = request.context.get_discussion_id() if not user_id: raise HTTPUnauthorized() req_permissions = request.GET.getall('permission') or [ P_READ, P_READ_PUBLIC_CIF] random_seed = request.GET.get('seed', None) if random_seed: # We need some determinism import random random.seed(random_seed) random_str = ''.join([chr(random.randint(0,256)) for i in range(8)]) random.seed(urandom(8)) else: random_str = urandom(8) if isinstance(req_permissions, list): req_permissions = set(req_permissions) else: req_permissions = set((req_permissions,)) permissions = set(get_permissions(user_id, discussion_id)) if not req_permissions: req_permissions = permissions else: if P_READ in permissions: permissions.add(P_READ_PUBLIC_CIF) if P_SYSADMIN not in permissions: req_permissions = list(req_permissions.intersection(permissions)) req_permissions = list(req_permissions) data = [str(user_id), str(discussion_id)] data.extend([str(x) for (x,) in Permission.db.query(Permission.id).filter( Permission.name.in_(req_permissions)).all()]) data = ','.join(data) + '.' + base64.urlsafe_b64encode(random_str) return Response(body=data_token(data), content_type="text/text")
def test_random(self,rounds): for i in range(rounds): if i+1 in (1,rounds) or not (i+1) % 10: msg('\rTesting random input data: {:4}/{} '.format(i+1,rounds)) dlen = int(os.urandom(4).hex(),16) >> 18 self.compare_hashes(dlen,os.urandom(dlen)) msg('OK\n')
def createKeyFileObj(self): #generate keys iv = str(makeIV(os.urandom(32))) #size = 16 keyAES = str(makeKeyAES(os.urandom(32))) #size = 32 rsaRandNum = str(os.urandom(32)) # size = 32 keyFileObj = DCFileKey(iv, keyAES, rsaRandNum) return keyFileObj
def sign_request(self, request): """Sign request per PBSAuth specifications. Keyword arguments: `request` -- instance of `urllib2.Request` Returns: instance of `urllib2.Request` (signed) """ timestamp = str(time.time()) try: nonce = urlsafe_b64encode(urandom(32)).strip("=") except TypeError: nonce = urlsafe_b64encode(urandom(32)).decode('utf-8').strip("=") query = request.get_full_url() to_be_signed = 'GET%s%s%s%s' % (query, timestamp, self.api_app_id, nonce) signature = hmac.new(self.api_app_secret.encode('utf-8'), to_be_signed.encode('utf-8'), sha1).hexdigest() request.add_header('X-PBSAuth-Timestamp', timestamp) request.add_header('X-PBSAuth-Consumer-Key', self.api_app_id) request.add_header('X-PBSAuth-Signature', signature) request.add_header('X-PBSAuth-Nonce', nonce) return request
def main(): parser = argparse.ArgumentParser(description='Create three possible base64 contents based on given string') parser.add_argument('-s','--stringplain',help='Plaintext string',required=True) parser.add_argument('-c','--customalphabet',help='Specify a custom alphabet',required=False) parser.add_argument('-32','--base32',help='Use base32 instead of base64',action='store_true',required=False) parser.add_argument('-u','--unicode',help='String is unicode',action='store_true',required=False) args = parser.parse_args() string_to_encode = args.stringplain base32 = args.base32 if base32: standard_base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' #standard base32 alphabet else: standard_base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' #standard base64 alphabet if args.customalphabet: alphabet = args.customalphabet if len(alphabet) != len(standard_base): print 'Custom alphabet must be same length as standard alphabet, exiting...' sys.exit(1) else: alphabet = standard_base if args.unicode: string_tmp = '' for c in string_to_encode: string_tmp += '%s\x00' % c string_to_encode = string_tmp.rstrip('\x00') for t in [3, 4, 5]: init_string1 = encode(os.urandom(t) + string_to_encode + os.urandom(6),alphabet,standard_base,base32) #initialize first string for i in range(100): init_string2 = encode(os.urandom(t) + string_to_encode + os.urandom(6),alphabet,standard_base,base32) init_string1 = longest(init_string1, init_string2) print 'content:"' + init_string1 + '";'
def encryption_oracle(text): #choose which mode to use m = random.randint(0,1) key =os.urandom(16) mode = AES.MODE_ECB encryptor = AES.new(key,mode) if(m == 0): #Choose EBC #key ='YELLOW SUBMARINE' #encryptor = AES.new(key,mode) crypt = encryptor.encrypt(text) print "ECB" + crypt.encode("hex") else: n=32 print "CBC" prev = os.urandom(16).encode("hex") testb = text.encode("hex") crypt = encrypt_cbc(testb,prev,n,encryptor) #Add 5-10 bytes randomly at the start r1= random.randint(5,10) #Add r1 bytes at the start start = os.urandom(r1) #do same for end bytes r2 = random.randint(5,10) end = os.urandom(r2) print r1, start.encode("hex"), r2, end.encode("hex") fin = start + crypt + end return fin
def createInvite(self, creatorId): h = hashlib.md5() h.update(os.urandom(1024)) h.update(str(creatorId)) h.update(self.salt) secret = h.digest() h.update(h.digest()) h.update(os.urandom(1024)) secret += h.digest() with self.connPool.item() as conn: with conn.cursor() as cur: try: cur.execute( "INSERT into invites (secret,inviter,creationdate) VALUES(%s,%s,timezone('UTC',CURRENT_TIMESTAMP));", (base64.urlsafe_b64encode(secret).replace("=", ""), creatorId), ) except psycopg2.IntegrityError as e: conn.rollback() # 'foreign_key_violation' - violation of 'inviter' foreign key # i.e. user with uid doesn't exist if e.pgcode == "23503": raise ValueError("User does not exist with that uid") self.log.exception("Failed creating invite", exc_info=True) raise except psycopg2.DatabaseError as e: conn.rollback() self.log.exception("Failed creating invite", exc_info=True) raise conn.commit() self.log.info("Created invite for user %.8x", creatorId) return fairywren.INVITE_FMT % secret
def service(request, name): if not request.user.profile.flags['dev']: raise PermissionDenied() service = Service.objects.filter(name=name, scope='TEST').first() if (service and service.admin_user != request.user) or \ (not service and name != 'add'): raise Http404 if request.method == 'POST': service_f = ServiceForm(request.POST, instance=service) service_new = service_f.save(commit=False) if not service: while True: name = 'test%s' % os.urandom(6).encode('hex') if not Service.objects.filter(name=name).count(): break service_new.name = name service_new.is_shown = False service_new.scope = 'TEST' service_new.secret_key = os.urandom(10).encode('hex') service_new.admin_user = request.user logger.warn('service.create: name=%s' % name, {'r': request}) else: logger.info('service.modify: name=%s' % name, {'r': request}) service_new.save() return redirect('/dev/main/') return render(request, 'dev/service.html', {'service': service})
def user(request, uid): if not request.user.profile.flags['dev']: raise PermissionDenied() user = User.objects.filter(username=uid, profile__test_only=True).first() if not user and uid != 'add': raise Http404 if request.method == 'POST': first_name = request.POST.get('first_name', 'TEST') last_name = request.POST.get('last_name', 'TEST') gender = request.POST.get('gender', '*H') birthday = request.POST.get('birthday', None) if not birthday: birthday = None test_point = int(request.POST.get('test_point', '0')) try: kaist_info = json.loads(request.POST.get('kaist_info', '')) kaist_id = kaist_info['kaist_uid'] except: kaist_info = {} kaist_id = "" if not user: while True: seed = os.urandom(4).encode('hex') email = '*****@*****.**' % seed if not User.objects.filter(email=email).count(): break while True: username = '******' % os.urandom(8).encode('hex') if not User.objects.filter(username=username).count(): break user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=seed) profile = UserProfile(user=user, email_authed=True, test_enabled=True, test_only=True) logger.warn('user.create: uid=%s' % username, {'r': request}) else: profile = user.profile logger.info('user.modify: uid=%s' % uid, {'r': request}) user.first_name = first_name user.last_name = last_name user.save() profile.gender = gender profile.birthday = birthday profile.test_point = test_point profile.set_kaist_info({'userid': kaist_id, 'kaist_info': kaist_info}) profile.save() return redirect('/dev/main/') return render(request, 'dev/user.html', {'tuser': user})
def put(self): allowed_routes = ['{{ function_name }}'] function = self.request.get('f') input_source = self.request.get('input1') json_data = {'f':function, 'input1':input_source} output = '' if self.request.get('output') == '': key_length = 16 # for now, randomly generates keys 16 chars long json_data['output'] = base64.b64encode(os.urandom(key_length)) # TODO - does this work in app engine? else: json_data['output'] = str(self.request.get('output')) output = str(json_data['output']) if function in allowed_routes: url = '/' + function logging.debug('starting a request for url ' + url) queue.put_message(get_queue('tasks'), json.dumps(json_data)) key_length = 16 task_name = base64.b64encode(os.urandom(key_length)) result = {'result':'success', 'task_id':task_name, 'output':output, 'id':task_name} logging.debug('result of job with input data' + str(json_data) + ' was ' + str(result)) self.response.out.write(json.dumps(result)) else: reason = 'Cannot add a task for function type ' + str(function) result ={'result':'failure', 'reason':reason} self.response.out.write(json.dumps(result))
def mk_token(self, load): ''' Run time_auth and create a token. Return False or the token ''' ret = self.time_auth(load) if ret is False: return {} fstr = '{0}.auth'.format(load['eauth']) hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5')) tok = str(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(self.opts['token_dir'], tok) while os.path.isfile(t_path): tok = str(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(self.opts['token_dir'], tok) fcall = salt.utils.format_call(self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) tdata = {'start': time.time(), 'expire': time.time() + self.opts['token_expire'], 'name': fcall['args'][0], 'eauth': load['eauth'], 'token': tok} if 'groups' in load: tdata['groups'] = load['groups'] with salt.utils.fopen(t_path, 'w+b') as fp_: fp_.write(self.serial.dumps(tdata)) return tdata
def _create_id_translator_keys(): return { "key" : os.urandom(_KEY_SIZE), "hmac_key" : os.urandom(_KEY_SIZE), "iv_key" : os.urandom(_KEY_SIZE), "hmac_size" : 16, }
def generate_csrf_token(self): part_1 = os.urandom(32).encode('hex') part_2 = os.urandom(32).encode('hex') shared = 'aabbccdd112233' return part_1 + shared + part_2
def test_AllLengthMessages(self): key = base64.urlsafe_b64encode(os.urandom(16)) fstl = MyFeistel(key, 10) for i in xrange(101): txt = os.urandom(i+1) dtxt = fstl.decrypt(fstl.encrypt(txt)) assert dtxt == txt
def _ResetTraceMap(): """This function gets called by savemap.py::SaveMap to clear trace data.""" global nextTraceId, traceKey, traceHeader nextTraceId = 0 traceKey = ut.b2i4(os.urandom(4)) traceMap.clear() traceHeader = os.urandom(16)
def test_pick_blocks(self): integer = random.randint(0, 65535) decimal_ = Decimal(random.random()) + 5 hashobj = hashlib.sha256(os.urandom(24)) hexdigest = hashlib.sha256(os.urandom(24)).hexdigest() seeds = self.hb.pick_blocks(4, integer) self.assertEqual(len(seeds), 4) seeds = self.hb.pick_blocks(4, decimal_) self.assertEqual(len(seeds), 4) for seed in seeds: self.assertIsInstance(seed, int) seeds = self.hb.pick_blocks(4, hashobj) self.assertEqual(len(seeds), 4) for seed in seeds: self.assertIsInstance(seed, int) seeds = self.hb.pick_blocks(4, hexdigest) self.assertEqual(len(seeds), 4) for seed in seeds: self.assertIsInstance(seed, int) with self.assertRaises(HeartbeatError) as ex: self.hb.pick_blocks(-1, integer) ex_msg = ex.exception.message self.assertEqual("-1 is not greater than 0", ex_msg)
def generate_keyfiles(n, m, vf, sf): '''Generate a set of public and private keys for testing. n - the number of OR loops m - the number of keys per loop (note: constant in this crude version) vf - the file path to which to write the verification keys sf - the file path to which to write the signing (private) keys ''' signing_indices = [random.choice(range(m)) for _ in range(n)] priv=[] with open(sf,'wb') as f: for i in range(n): priv.append(os.urandom(32)) f.write(binascii.hexlify(priv[i])+'\n') with open(vf,'wb') as f: for i in range(n): pubkeys = [] for j in range(m): if j==signing_indices[i]: p = btc.privtopub(priv[i]) else: p = btc.privtopub(os.urandom(32)) p = btc.decode_pubkey(p) p = btc.encode_pubkey(p,'bin_compressed') pubkeys.append(binascii.hexlify(p)) f.write(','.join(pubkeys)+'\n')
def create_room(self): self.hawk_room_owner = self.hawk_auth data = { "roomName": "UX Discussion", "expiresIn": 1, "roomOwner": "Alexis", "maxSize": MAX_NUMBER_OF_PEOPLE_JOINING, } if random.randint(0, 100) < PERCENTAGE_OF_ROOM_CONTEXT: del data["roomName"] data["context"] = { "value": b64encode(os.urandom(1024)).decode("utf-8"), "alg": "AES-GCM", "wrappedKey": b64encode(os.urandom(16)).decode("utf-8"), } self.incr_counter("room-with-context") resp = self.session.post( self.base_url + "/rooms", data=json.dumps(data), headers={"Content-Type": "application/json"}, auth=self.hawk_room_owner, ) self.assertEquals( 201, resp.status_code, "Room Creation failed with code %s: %s" % (resp.status_code, resp.content) ) self.incr_counter("create-room") data = self._get_json(resp) return data.get("roomToken")
def test_close(self): random.shuffle(self.swarm) alice = self.swarm[0] bob = self.swarm[1] # open stream hexstreamid = alice.stream_open(bob.dht_id()) self.assertIsNotNone(hexstreamid) # transfer works before written_hexdata = binascii.hexlify(os.urandom(32)) bytes_written = alice.stream_write(hexstreamid, written_hexdata) self.assertEqual(bytes_written, 32) read_hexdata = bob.stream_read(hexstreamid) self.assertEqual(read_hexdata, written_hexdata) # test close self.assertTrue(alice.stream_close(hexstreamid)) # write fails on closed stream written_hexdata = binascii.hexlify(os.urandom(32)) bytes_written = alice.stream_write(hexstreamid, written_hexdata) self.assertEqual(bytes_written, None) # read fails on closed stream read_hexdata = bob.stream_read(hexstreamid) self.assertEqual(read_hexdata, None)
def _deleteLocalFileFn(job, nonLocalDir): """ Test deleteLocalFile on a local write, non-local write, read, mutable read, and bogus jobstore IDs. """ work_dir = job.fileStore.getLocalTempDir() # Write local file with open(os.path.join(work_dir, str(uuid4())), 'w') as localFile: localFile.write(os.urandom(1 * 1024 * 1024)) localFsID = job.fileStore.writeGlobalFile(localFile.name) # write Non-Local File with open(os.path.join(nonLocalDir, str(uuid4())), 'w') as nonLocalFile: nonLocalFile.write(os.urandom(1 * 1024 * 1024)) nonLocalFsID = job.fileStore.writeGlobalFile(nonLocalFile.name) # Delete fsid of local file. The file should be deleted job.fileStore.deleteLocalFile(localFsID) assert not os.path.exists(localFile.name) # Delete fsid of non-local file. The file should persist job.fileStore.deleteLocalFile(nonLocalFsID) assert os.path.exists(nonLocalFile.name) # Read back one file and then delete it readBackFile1 = job.fileStore.readGlobalFile(localFsID) job.fileStore.deleteLocalFile(localFsID) assert not os.path.exists(readBackFile1) # Read back one file with 2 different names and then delete it. Assert both get deleted readBackFile1 = job.fileStore.readGlobalFile(localFsID) readBackFile2 = job.fileStore.readGlobalFile(localFsID) job.fileStore.deleteLocalFile(localFsID) assert not os.path.exists(readBackFile1) assert not os.path.exists(readBackFile2) # Try to get a bogus FSID try: job.fileStore.readGlobalFile('bogus') except NoSuchFileException: pass
def test_io(self): random.shuffle(self.swarm) alice = self.swarm[0] bob = self.swarm[1] # open stream hexstreamid = alice.stream_open(bob.dht_id()) self.assertIsNotNone(hexstreamid) # write alice to bob alice_hexdata = binascii.hexlify(os.urandom(32)) bytes_written = alice.stream_write(hexstreamid, alice_hexdata) self.assertEqual(bytes_written, 32) # write bob to alice bob_hexdata = binascii.hexlify(os.urandom(32)) bytes_written = bob.stream_write(hexstreamid, bob_hexdata) self.assertEqual(bytes_written, 32) # read alice from bob read_data = alice.stream_read(hexstreamid) self.assertEqual(read_data, bob_hexdata) # read bob from alice read_data = bob.stream_read(hexstreamid) self.assertEqual(read_data, alice_hexdata) # close stream self.assertTrue(alice.stream_close(hexstreamid))
def testBinaryLimits(self): # REST Does not support binary data types at this time. if self.dsn == "ODBC": with udaExec.connect(self.dsn, username=self.username, password=self.password) as conn: self.assertIsNotNone(conn) cursor = conn.execute( """CREATE TABLE testBinaryLimits (id INTEGER, a BYTE, c VARBYTE(10000), e BLOB (2000000))""") cursor.arraysize = 10 params = [ (101, bytearray(os.urandom(1)), bytearray(os.urandom(10000)), bytearray(os.urandom(2000000))), (102, None, None, None)] for p in params: conn.execute( "INSERT INTO testBinaryLimits " "VALUES (?, ?, ?, ?)", p) cursor = conn.execute("SELECT * FROM testBinaryLimits") for desc in cursor.description: print(desc) for desc in cursor.types: print(desc) rowIndex = 0 for row in cursor: colIndex = 0 for col in row: self.assertEqual(col, params[rowIndex][colIndex]) colIndex += 1 rowIndex += 1
def __init__(self, test_folder, options): self.test_folder = os.path.join(test_folder, "tester") self.options = options self.config = Config.get_config() self.store_folder = os.path.join(self.test_folder, "stores") self.files_folder = os.path.join(self.test_folder, "files") self.restore_folder = os.path.join(self.test_folder, "restore") self.db = DB() self.max_fs_id = self.db.query("select max(fs_id) from fs", ())[0][0] if self.max_fs_id is None: self.max_fs_id = 0 self.max_version_id = self.db.query("select max(version_id) from versions", ())[0][0] if self.max_version_id is None: self.max_version_id = 0 self.max_run_id = self.db.query("select max(run_id) from runs", ())[0][0] if self.max_run_id is None: self.max_run_id = 0 self.max_message_id = self.db.query("select max(message_id) from messages", ())[0][0] if self.max_message_id is None: self.max_message_id = 0 log.debug("MAX IDs", self.max_fs_id, self.max_version_id, self.max_run_id, self.max_message_id) self.teststring1 = os.urandom(204800) self.teststring2 = os.urandom(204800)
def test_something(self): res = self.session.get('http://localhost:9000') self.assertTrue('chatform' in res.content) results = [] def callback(m): results.append(m.data) ws = self.create_ws('ws://localhost:9000/ws', protocols=['chat', 'http-only'], callback=callback) one = 'something' + os.urandom(10).encode('hex') two = 'happened' + os.urandom(10).encode('hex') ws.send(one) ws.receive() ws.send(two) ws.receive() start = time.time() while one not in results and two not in results: gevent.sleep(0) if time.time() - start > 1: raise AssertionError('Too slow')
def generate_from_raw(comment, password, raw_pub, raw_priv): """ADVANCED: Given a raw Ed25519 key pair raw_pub and raw_priv, create a Signify keypair. See generate() for documentation. """ assert isinstance(raw_pub, bytes) assert isinstance(raw_priv, bytes) if comment is None: comment = "signify" keynum = os.urandom(8) # private key kdfrounds = 42 salt = os.urandom(16) if password is None: kdfrounds = 0 xorkey = b"\x00" * 64 else: xorkey = bcrypt.kdf(password, salt, 64, kdfrounds) protected_key = xorbuf(xorkey, raw_priv) checksum = hashlib.sha512(raw_priv).digest()[0:8] priv_blob = b"Ed" + b"BK" + struct.pack("!L", kdfrounds) + salt + checksum + keynum + protected_key priv = _Materialized.write_message("%s secret key" % (comment,), priv_blob) # public key pub_blob = b"Ed" + keynum + raw_pub pub = _Materialized.write_message("%s public key" % (comment,), pub_blob) return PublicKey.from_bytes(pub), SecretKey.from_bytes(priv)
def sometx(): secret = "A" * 32 public = rscoin.Key(secret, public=False).id() directory = [(public, "127.0.0.1", 8080)] factory = RSCFactory(secret, directory, None) # Build one transaction k1 = rscoin.Key(urandom(32), public=False) k2 = rscoin.Key(urandom(32), public=False) tx1 = rscoin.Tx([], [rscoin.OutputTx(k1.id(), 100)]) tx2 = rscoin.Tx([], [rscoin.OutputTx(k2.id(), 150)]) tx3 = rscoin.Tx([rscoin.InputTx(tx1.id(), 0), rscoin.InputTx(tx2.id(), 0)], [rscoin.OutputTx(k1.id(), 250)]) for kv, vv in tx1.get_utxo_out_entries() + tx2.get_utxo_out_entries(): factory.db[kv] = vv # Run the protocol instance = factory.buildProtocol(None) tr = StringTransport() instance.makeConnection(tr) return (factory, instance, tr), (k1, k2, tx1, tx2, tx3)
from flask_socketio import SocketIO, emit import psycopg2 import psycopg2.extras from collections import OrderedDict import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from db import * import uuid import string import random app = Flask(__name__) socketio = SocketIO(app) app.secret_key = os.urandom(24).encode('hex') globalDict = {'accessCode': ''} #Queries loginQuery = "SELECT passwordid FROM login WHERE password = crypt(%s, password)" updatePasswordQuery = "UPDATE login SET password=crypt(%s, gen_salt('bf')) WHERE passwordid = 1" studentTable = "INSERT INTO students(email, firstName, lastName, hasCar, passengers) VALUES (%s, %s, %s, %s, %s)" endorseTable = "INSERT INTO endorsements(endorsementName, studentemail) VALUES (%s, %s)" meetingTable = "SELECT meetingid from meetinday where " meetingAddon = "%s = %s" meetingInsert = "INSERT INTO meetingdays(monday, tuesday, wednesday, thursday, friday) VALUES (%s, %s, %s, %s, %s) RETURNING meetingid" prevPracTable = "INSERT INTO previousPractica(school,grade,course,studentEmail) VALUES (%s, %s, %s, %s)" enrolledCourseTable = "INSERT INTO enrolledCourses(courseName,studentEmail) VALUES (%s, %s)" availableInsert = "INSERT INTO availabletimes (starttime, endtime, meetingid, studentemail) VALUES (%s, %s, %s, %s)"
from AES import AESCTRencrypt import os key = os.urandom(16) def readFileandEncrypt(filename): encrypted = [] with open(filename, 'r') as myfile: for line in myfile: message = line.decode("base64").encode("hex") encrypted.append(AESCTRencrypt(key, message, 0)) return encrypted
def generate_secret_for_hacker_with_email(email): return base64.urlsafe_b64encode( email.encode('utf-8') + ',' + os.urandom(64))
def _generate_key(cls): return os.urandom(32)
def create_dummy_file(filename, dir_path="/tmp"): os.makedirs(dir_path, exist_ok=True) full_path = os.path.join(dir_path, filename) with open(full_path, "wb") as f: f.write(os.urandom(1 * 1024 * 1024))
import asyncio import time from flask import Flask, jsonify from flask_cors import CORS from flask_socketio import SocketIO, emit import eventlet eventlet.monkey_patch() import rq_dashboard from quoter import Quoter app = Flask(__name__) app.secret_key = binascii.hexlify(os.urandom(24)) socketio = SocketIO(app, async_mode='eventlet', cors_allowed_origins="*", engineio_logger=True) #setup rq dashboard app.config.from_object(rq_dashboard.default_settings) app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rq") @socketio.on('connect') def test_connect(): print('Client connected') emit('connect', 'Connected to Flask-SocketIO') @socketio.on('disconnect') def test_disconnect(): print('Client disconnected')
from application.drinks import views from application.ingredients import models from application.ingredients import views from application.keywords import models from application.keywords import views from application.search import views from application.profile import views from application.admin import views from application.auth import models from application.auth import views from application.auth import role # kirjautuminen from application.auth.models import User from os import urandom app.config["SECRET_KEY"] = urandom(32) @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) # Luodaan lopulta tarvittavat tietokantataulut db.create_all()
def generate_key(self): return binascii.hexlify(os.urandom(20)).decode()
def generate_random_hash(): return hashlib.md5(os.urandom(32)).hexdigest()
def createSecretKey(self, size): return (''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(size))))[0:16]
def create_random_16(self): '''获取随机十六个字母拼接成的字符串''' return (''.join(map(lambda xx: (hex(ord(xx))[2:]), str(os.urandom(16)))))[0:16]
def _object_info(): length = 0 while length < (1024 * 1024): yield os.urandom(resp_chunk_size) length += resp_chunk_size
from os import urandom from hashlib import sha512 from uuid import uuid4 from re import search from time import gmtime, strftime import sqlite3 # a 32-byte key that should be used to secure the Flask session secret_key = urandom(32) # checks whether the database contains a user with the given information def check_login_info(username, password): # Create the connection and cursor for the SQLite database. conn = sqlite3.connect("data.db") c = conn.cursor() # If the user_info table doesn't exist, return false. q = 'SELECT name FROM sqlite_master WHERE \ TYPE = "table" AND NAME = "user_info"' c.execute(q) if not c.fetchone(): return False # If the table does exist, check the given username and password. q = 'SELECT salt, hash_value FROM user_info WHERE username = ?' salt_n_hash = c.execute(q, (username, )).fetchone() # If the username does not exist, return false. if not salt_n_hash: return False # If the password is wrong, return false. if (sha512(
def before_request(): g.request_uid = binascii.b2a_hex(os.urandom(20)) g.request_start_time = time.time() log_app("request\t%s\t%s\t%s" % (request.url, request.method, get_current_team_id()))
def make_keys(p, g): x = int(os.urandom(4).encode('hex'), 16) % p return x, pow(g, x, p) #(g**x) % p
def random_string(n): return os.urandom(n).encode("hex")
testaddr = b58encode(addr[0] + part1 + part2) if args.destaddr != testaddr or outscript not in tx: raise Exception("Corrupted destination address! Check your RAM!") get_consent("I am sending coins on the %s network and I accept the risks" % coin.fullname) print "generated transaction", txhash[::-1].encode("hex") print "\n\nConnecting to servers and pushing transaction\nPlease wait for a minute before stopping the script to see if it entered the server mempool.\n\n" client = Client(coin) client.connect() services = 0 localaddr = "\x00" * 8 + "00000000000000000000FFFF".decode("hex") + "\x00" * 6 nonce = os.urandom(8) user_agent = "Scraper" msg = struct.pack("<IQQ", coin.versionno, services, int(time.time())) + localaddr + localaddr + nonce + lengthprefixed(user_agent) + struct.pack("<IB", 0, 0) client.send("version", msg) while True: cmd, payload = client.recv_msg() print "received", cmd, "size", len(payload) if cmd == "version": client.send("verack", "") elif cmd == "sendheaders": msg = make_varint(0) client.send("headers", msg) elif cmd == "ping":
def nonce(size=48, encoding='base64url'): raw = os.urandom(size) if encoding == 'base64url': return base64.urlsafe_b64encode(raw).strip() else: return raw.encode(encoding).strip()
def generate_random(chars): print ( codecs.encode ( os.urandom(int(chars)), 'hex') )
def test_create_key_cryptography(self): b_password = b'hunter42' b_salt = os.urandom(32) b_key_cryptography = self.vault_cipher._create_key_cryptography( b_password, b_salt, key_length=32, iv_length=16) self.assertIsInstance(b_key_cryptography, six.binary_type)
def make_secret(password): salt = os.urandom(4) h = hashlib.sha1(password.encode("utf-8")) h.update(salt) return "{SSHA}".encode("utf-8") + b64encode(h.digest() + salt)
class Config: ACCOUNTS_COUNT = 300 ACCOUNT_RESERVE_TIMEOUT = 15 # Minutes COURSE_SCAN_INTERVAL = 60 * 24 * 15 # Minutes DATABASE_HOST = None DATABASE_NAME = "database.db" DATABASE_PASSWORD = None DATABASE_PORT = None DATABASE_TYPE = "SQLite" DATABASE_USER = None DEFAULT_API_LIST_LIMIT = 20 INTERVAL_BETWEEN_QUESTIONS = 7 # Seconds (in tests_solver.wait_timeout) INTERVAL_BETWEEN_SESSION_CHECK = 5 # Seconds (in tests_solver.get_or_create_question) INTUIT_SSL_VERIFY = True GRAYLOG_HOST = None LATENCY_STEP_INCREASE_BETWEEN_SIMILAR_QUESTIONS = 10 # seconds MAX_ACCOUNT_AGE = 60 * 24 * 1000 # Minutes MAX_API_LIST_LIMIT = 50 MAX_ITERATIONS_OF_RECEIVING_QUESTIONS = 10 # tests_solver.get_passed_questions_and_answers MAX_LATENCY_FOR_OUT_OF_SYNC = 30 # Seconds MAX_LATENCY_FOR_SESSION_CHECKS = 300 # Seconds (after this time question will be forcibly selected) SESSION_ID = sha3_256(urandom(256)).hexdigest() STATIC_DIRECTORY = "static" TEST_SCAN_INTERVAL = 900 # Seconds TEST_SOLVER_SESSION_QUEUE_HOST = None WEBSITE = "https://www.intuit.ru" @staticmethod def update(): """Updates config from files and environment""" dict_config = get_user_config() for key, value in dict_config.items(): setattr(Config, key, value) @classmethod def get_static_directory_path(cls): """Returns the static directory as Path type and create if it isn't exists""" path = Path(cls.STATIC_DIRECTORY) if not path.exists(): makedirs(str(path)) return path @classmethod def get_account_aging_moment(cls) -> datetime: """Returns datetime which contains a moment of the account aging""" return sub_timedelta(timedelta(minutes=cls.MAX_ACCOUNT_AGE)) @classmethod def get_account_reserve_out_moment(cls) -> datetime: """Returns datetime which contains a moment of the account timeout""" return sub_timedelta(timedelta(minutes=cls.ACCOUNT_RESERVE_TIMEOUT)) @classmethod def get_course_scan_timeout_moment(cls) -> datetime: """Returns datetime which contains a moment of the course update timeout""" return sub_timedelta(timedelta(minutes=cls.COURSE_SCAN_INTERVAL)) @classmethod def get_test_scan_timeout_moment(cls) -> datetime: """Returns datetime a moment of the timeout gone""" return sub_timedelta(timedelta(seconds=cls.TEST_SCAN_INTERVAL))
def flip(): return os.urandom(1)[0] & 1
from c18_Implement_CTR_mode import AES_CTR, XOR_with_Key from c19_Break_fixed_nonce_CTR_mode_using_substitutions import get_keyString, Fix_keyString from pwn import p64 from base64 import b64decode import os KEY = os.urandom(16) nonce = p64(0) BLOCK_SIZE = 16 def main(): plainlist = open("Challenge20.txt", "r").readlines() plainlist = [b64decode(x) for x in plainlist] cipherlist = [AES_CTR(x, KEY, nonce) for x in plainlist] maxLen = max([len(x) for x in cipherlist]) print("maxLen : %d " % maxLen) nColumnCipher = [] for n in range(0, maxLen): nColumn = "" for c in cipherlist: if len(c) > n: nColumn += c[n] nColumnCipher.append(nColumn) keyString = get_keyString(nColumnCipher) keyString = Fix_keyString(keyString, cipherlist[0], "I'm rated \"R\"...this is a warning, ya better void / Poets are paranoid, DJ's D-stroyed") keyString = Fix_keyString(keyString, cipherlist[5], "Music's the clue, when I come your warned / Apocalypse How, when I'm done, ya gone!") keyString = Fix_keyString(keyString, cipherlist[59], "And we outta here / Yo, what happened to peace? / Peace")
def get(privateKey): rand = os.urandom(128) return pack(crypto.unhexlify(crypto.getSignatureFromBytes(seed()+rand, privateKey)), rand)
@app.route('/preengage', methods=['GET', 'POST']) def pre_questions(): array1 = [] array2 = [] if request.method == 'GET': db = MySQLdb.connect(host, user, password, database) cursor = db.cursor() cursor.execute("Select question_id, question from prequestions") questions = cursor.fetchall() for row in questions: array1.append({"Question_id": row[0], "Question": row[1]}) cursor.execute("Select mile_id, milestone from milestone") milestones = cursor.fetchall() for row in milestones: array2.append({"Milestone_id": row[0], "Milestone": row[1]}) result = [{"Questionaires": array1, "Milestones": array2}] cursor.close() return jsonify(result) @app.route("/logout") def logout(): session['logged_in'] = False return home() if __name__ == "__main__": app.secret_key = os.urandom(12) app.run(debug=True, host='0.0.0.0', port=4000)
def send_mail( subject=None, text=None, interval=None, channel=None, to=None, extra_headers=None, attachments=None, timeout=300, queue=True, ): from freenasUI.account.models import bsdUsers from freenasUI.system.models import Email syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) if interval is None: interval = timedelta() if not channel: channel = get_sw_name().lower() if interval > timedelta(): channelfile = '/tmp/.msg.%s' % (channel) last_update = datetime.now() - interval try: last_update = datetime.fromtimestamp(os.stat(channelfile).st_mtime) except OSError: pass timediff = datetime.now() - last_update if (timediff >= interval) or (timediff < timedelta()): # Make sure mtime is modified # We could use os.utime but this is simpler! with open(channelfile, 'w') as f: f.write('!') else: return True, 'This message was already sent in the given interval' error = False errmsg = '' em = Email.objects.all().order_by('-id')[0] if not to: to = [bsdUsers.objects.get(bsdusr_username='******').bsdusr_email] if not to[0]: return True, 'Email address for root is not configured' if attachments: msg = MIMEMultipart() msg.preamble = text list(map(lambda attachment: msg.attach(attachment), attachments)) else: msg = MIMEText(text, _charset='utf-8') if subject: msg['Subject'] = subject msg['From'] = em.em_fromemail msg['To'] = ', '.join(to) msg['Date'] = formatdate() local_hostname = _get_local_hostname() msg['Message-ID'] = "<%s-%s.%s@%s>" % (get_sw_name().lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"), base64.urlsafe_b64encode(os.urandom(3)), local_hostname) if not extra_headers: extra_headers = {} for key, val in list(extra_headers.items()): if key in msg: msg.replace_header(key, val) else: msg[key] = val try: server = _get_smtp_server(timeout, local_hostname=local_hostname) # NOTE: Don't do this. # # If smtplib.SMTP* tells you to run connect() first, it's because the # mailserver it tried connecting to via the outgoing server argument # was unreachable and it tried to connect to 'localhost' and barfed. # This is because FreeNAS doesn't run a full MTA. # else: # server.connect() syslog.syslog("sending mail to " + ','.join(to) + msg.as_string()[0:140]) server.sendmail(em.em_fromemail, to, msg.as_string()) server.quit() except ValueError as ve: # Don't spam syslog with these messages. They should only end up in the # test-email pane. errmsg = str(ve) error = True except Exception as e: errmsg = str(e) log.warn('Failed to send email: %s', errmsg, exc_info=True) error = True if queue: with MailQueue() as mq: mq.append(msg) except smtplib.SMTPAuthenticationError as e: errmsg = "%d %s" % (e.smtp_code, e.smtp_error) error = True except: errmsg = "Unexpected error." error = True return error, errmsg
#Erik added these from sklearn.model_selection import train_test_split, cross_val_predict, cross_val_score, cross_validate from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix, accuracy_score, f1_score from sklearn import svm, datasets from sklearn.utils.multiclass import unique_labels from sklearn.externals import joblib from sklearn import preprocessing ###################################### # EB looks for an 'application' callable by default. application = Flask(__name__) #wtf secret key SECRET_KEY = os.urandom(32) application.config['SECRET_KEY'] = SECRET_KEY times_wanted = ['0', '23', '47', '71'] predictors_wanted = [['draw_'+time, 'home_away_diff_'+time] for time in times_wanted] predictors_wanted = [item for sublist in predictors_wanted for item in sublist] colms_wanted = predictors_wanted.copy() colms_wanted.append('outcome') colms_wanted.append('league') colms_wanted_as_str = ', '.join(colms_wanted) # A database class to use the DB as an object class Database: def __init__(self): host = 'btb-db-instance.cduiw3cccdch.us-east-1.rds.amazonaws.com'
def test(): global vm global trigger global media global trigger_action vm = test_stub.create_vm() vm.check() vm_ip = vm.get_vm().vmNics[0].ip vm_uuid = vm.get_vm().uuid vm_username = os.environ.get('Vm_Username') vm_password = os.environ.get('Vm_Password') vm_port = os.environ.get('Vm_Sshport') test_item = "vm.network.io" resource_type = "VmInstanceVO" vm_monitor_item = test_stub.get_monitor_item(resource_type) if test_item not in vm_monitor_item: test_util.test_fail('%s is not available for monitor' % test_item) duration = 20 expression = "vm.network.io{direction=\"tx\"} > 10" monitor_trigger = mon_ops.create_monitor_trigger(vm_uuid, duration, expression) send_email = test_stub.create_email_media() media = send_email.uuid trigger_action_name = "trigger_" + ''.join( map(lambda xx: (hex(ord(xx))[2:]), os.urandom(8))) trigger = monitor_trigger.uuid receive_email = os.environ.get('receive_email') monitor_trigger_action = mon_ops.create_email_monitor_trigger_action( trigger_action_name, send_email.uuid, trigger.split(), receive_email) trigger_action = monitor_trigger_action.uuid ssh_cmd = test_stub.ssh_cmd_line(vm_ip, vm_username, vm_password, vm_port) test_stub.yum_install_stress_tool(ssh_cmd) test_stub.run_iperf_server(ssh_cmd) hosts = res_ops.get_resource(res_ops.HOST) host = hosts[0] host.password = os.environ.get('hostPassword') test_stub.yum_install_stress_tool(ssh_cmd) t = threading.Thread(target=test_stub.run_network_tx, args=(ssh_cmd, host.managementIp)) t.start() time.sleep(110) test_stub.kill(ssh_cmd) status_problem, status_ok = test_stub.query_trigger_in_loop(trigger, 50) test_util.action_logger( 'Trigger old status: %s triggered. Trigger new status: %s recovered' % (status_problem, status_ok)) if status_problem != 1 or status_ok != 1: test_util.test_fail( '%s Monitor Test failed, expected Problem or OK status not triggered' % test_item) mail_list = test_stub.receive_email() keywords = "fired" mail_flag = test_stub.check_email(mail_list, keywords, trigger, vm_uuid) if mail_flag == 0: test_util.test_fail('Failed to Get Target: %s for: %s Trigger Mail' % (vm_uuid, test_item)) mon_ops.delete_monitor_trigger_action(trigger_action) mon_ops.delete_monitor_trigger(trigger) mon_ops.delete_email_media(media) vm.destroy()
def generate_key_string(cls, key_size=192): key = os.urandom(key_size // 8 + cls.SIG_SIZE) return key.encode('base64').replace('\n', '')