def __init__(self, known_pattern=None, session=db_session): '''Instantiates a color game based on a random color pattern. If known_pattern is specified, this color pattern is used to create the game instead of a random pattern. This should only be used for testing purposes. If session is specified, this DB session is used instead of the standard session. :param known_pattern: a list (or tuple) of one-letter colors (default: None) :param session: the DB session (default: standard color game session) ''' # Make sure to cleanup database resources on exit register(self._cleanup) # Set up DB session self.s = session if known_pattern is None: sr = SystemRandom() self.pattern = [sr.choice(colors_short) for _ in range(PATTERN_LENGTH)] else: self.pattern = known_pattern self.pattern_set = set(self.pattern) self.game = ColorGame(pattern=ColorPattern(self.pattern)) self.s.add(self.game) self.s.commit()
def generate_groups(self): """ Generates the groups based on a randomization algorithm. :return: the generated groups: a list of lists (names) """ if not self.names: raise AttributeError("Could not find names list. Try re-initializing Engine with valid filepath.") groups = [] cryptogen = SystemRandom() cryptogen.shuffle(self.names) current_group = [] for name in self.names: current_group.append(name) is_last_name = self.names.index(name) == len(self.names) - 1 is_group_full = len(current_group) == self.group_size if is_group_full or is_last_name: groups.append(current_group) current_group = [] logging.info("Created {} groups with max size {}.".format(len(groups), self.group_size)) return groups
def get_passphrase(wordnum=6, specialsnum=1, delimiter='', lang='en', capitalized=True, wordlist_fd=None): """Get a diceware passphrase. The passphrase returned will contain `wordnum` words deliimted by `delimiter`. If `capitalized` is ``True``, all words will be capitalized. If `wordlist_fd`, a file descriptor, is given, it will be used instead of a 'built-in' wordlist (and `lang` will be ignored). `wordlist_fd` must be open for reading. The wordlist to pick words from is determined by `lang`, representing a language (unless `wordlist_fd` is given). """ if wordlist_fd is None: wordlist_fd = open(get_wordlist_path(lang), 'r') word_list = get_wordlist(wordlist_fd) rnd = SystemRandom() words = [rnd.choice(word_list) for x in range(wordnum)] if capitalized: words = [x.capitalize() for x in words] result = delimiter.join(words) for _ in range(specialsnum): result = insert_special_char(result, rnd=rnd) return result
def random_password(description, min_chars=10, max_chars=20): """ Creates a random password from uppercase letters, lowercase letters and digits with a length between min_chars and max_chars """ # Open saved passwords file or create new one. try: fh = open("info/passwords.json", "r+") passwords = json.load(fh) except IOError: fh = open("info/passwords.json", "w+") passwords = {} # Return password if it exists already if description in passwords: fh.close() return passwords[description] # Create new password if it does not exist else: seeded_random = SystemRandom() chars = ascii_letters + digits password_length = seeded_random.randint(min_chars, max_chars) password = "".join(seeded_random.choice(chars) for _ in range(password_length)) passwords[description] = password fh.seek(0) json.dump(passwords, fh, indent=4) fh.close() return password
def generate_config(self, env_script, start_script, server_cert=None): """Generates the plugin configuration file Parameters ---------- env_script : str The CLI call used to load the environment in which the plugin is installed start_script : str The script used to start the plugin server_cert : str, optional If the Qiita server used does not have a valid certificate, the path to the Qiita certificate so the plugin can connect over HTTPS to it """ logger.debug('Entered BaseQiitaPlugin.generate_config()') sr = SystemRandom() chars = ascii_letters + digits client_id = ''.join(sr.choice(chars) for i in range(50)) client_secret = ''.join(sr.choice(chars) for i in range(255)) server_cert = server_cert if server_cert else "" with open(self.conf_fp, 'w') as f: f.write(CONF_TEMPLATE % (self.name, self.version, self.description, env_script, start_script, self._plugin_type, self.publications, server_cert, client_id, client_secret))
def getFiles(gendpointDict, uendpoint, username, upath): label = str(uuid4()) endNames = gendpointDict.keys() for thisEndName in endNames: fileList = gendpointDict[thisEndName] cryptogen = SystemRandom() transferFile = '/tmp/transferList_' + thisEndName + '_' + str(cryptogen.randint(1,9999)) + '.txt' file = open(transferFile, 'w') for thisFile in fileList: basename = os.path.basename(thisFile) if upath[-1] != '/': basename = '/' + basename remote = thisFile local = upath + basename file.write(remote + ' ' + local + '\n') file.close() os.system("globus transfer "+thisEndName+" "+uendpoint+" --batch --label \"CLI Batch\" < "+transferFile) os.remove(transferFile) return
def generate_password(self): import string from random import SystemRandom rnd = SystemRandom() # use SystemRandom to get real random numbers chars = string.letters + string.digits length = 20 return "".join(rnd.choice(chars) for _ in range(length))
def get_session(self): """ get current session associated with this request. if no current session, create a new session """ if self.__session: return self.__session if "SESSIONID" in self.cookie: self.__sid = self.cookie["SESSIONID"].value else: rand = SystemRandom() rand_num = rand.random() self.__sid = md5.new(repr(rand_num)).hexdigest() self.__new_session_hook() if not os.path.exists("/tmp/.session"): os.mkdir("/tmp/.session") self.__session_file = shelve.open( "/tmp/.session/yagra_session_db", writeback=True) if self.__sid not in self.__session_file: self.__session_file[self.__sid] = {} self.__session = self.__session_file[self.__sid] return self.__session
def csprng(low, high, offset=0): rng = SystemRandom() rnum = rng.randint(low, high-1) + offset if rnum < 0: print("[-] Error: Random number generator returned out of bounds.") return None return rnum
def generate(word_list, words=5, specials=0): rnd = SystemRandom() words = [ rnd.choice(word_list) for _ in range(words) ] # Insert at most options.special special characters. This is not # exactly the procedure described in the Diceware web page, because # this handles the case where there are more than 6 words in the # passphrase and more than 6 characters in the word. if specials: split_words = [ map(None, x) for x in words ] for _ in range(specials): # i is the index of the word in which the special character # replacement takes place. i = rnd.randrange(len(split_words)) # j is the index of the character to be replaced with a special # character. j = rnd.randrange(len(split_words[i])) # k is the index of the special character k = rnd.randrange(len(SPECIAL_CHARS)) # Split to individual characters, replace the k'th char, unsplit split_words[i][j] = SPECIAL_CHARS[k] with_specials = [ "".join(x) for x in split_words ] else: with_specials = words return words, with_specials
def get_encrypted_password(password, hashtype='sha512', salt=None): # TODO: find a way to construct dynamically from system cryptmethod= { 'md5': '1', 'blowfish': '2a', 'sha256': '5', 'sha512': '6', } if hashtype in cryptmethod: if salt is None: r = SystemRandom() if hashtype in ['md5']: saltsize = 8 else: saltsize = 16 salt = ''.join([r.choice(string.ascii_letters + string.digits) for _ in range(saltsize)]) if not HAS_PASSLIB: if sys.platform.startswith('darwin'): raise errors.AnsibleFilterError('|password_hash requires the passlib python module to generate password hashes on Mac OS X/Darwin') saltstring = "$%s$%s" % (cryptmethod[hashtype],salt) encrypted = crypt.crypt(password, saltstring) else: if hashtype == 'blowfish': cls = passlib.hash.bcrypt; else: cls = getattr(passlib.hash, '%s_crypt' % hashtype) encrypted = cls.encrypt(password, salt=salt) return encrypted return None
def client_func(E, P, Q): n = E.order gen = SystemRandom() an = gen.randrange(n) bn = gen.randrange(n) am = an bm = bn Xn = P*an + Q*bn Xm = Xn while (True): i = __H(Xn, L) Xn += R[i] an += c[i] bn += d[i] for j in range(2): h = __H(Xm, L) Xm += R[h] am += c[h] bm += d[h] if Xn == Xm: break if (bn == bm): raise ArithmeticError('Undefined value') f = an-am g = invmod(bm-bn, n) ret = (f * g) % n ret = (ret + n) % n sendToServer(ret)
def __init__(self, config, director, scheduler, _reactor=reactor): self._reactor = reactor self.director = director self.scheduler = scheduler self.config = config self.measurement_path = FilePath(config.measurements_directory) # We use a double submit token to protect against XSRF rng = SystemRandom() token_space = string.letters+string.digits self._xsrf_token = b''.join([rng.choice(token_space) for _ in range(30)]) self._director_started = False self._is_initialized = config.is_initialized() # We use exponential backoff to trigger retries of the startup of # the director. self._director_startup_retries = 0 # Maximum delay should be 30 minutes self._director_max_retry_delay = 30*60 self.status_poller = LongPoller( self._long_polling_timeout, _reactor) self.director_event_poller = LongPoller( self._long_polling_timeout, _reactor) # XXX move this elsewhere self.director_event_poller.start() self.status_poller.start() self.director.subscribe(self.handle_director_event) if self._is_initialized: self.start_director()
def check_collisions(upper_bound): """ Function that keeps guessing random numbers 1 to N incluside, until it hits a collision (or doesn't) """ cryptogen = SystemRandom() # OS Internal system for generating cryptographic random numbers already_found = set([]) # Set of numbers the adversary already found iterations = 1 start = time.time() found = False try: while not found: # Runs until a collision is found item = cryptogen.randrange(1,upper_bound) # Uses the cryptographically secure PRNG to generate a random number if item in already_found: # If it's in the set of things already found - print the statistics found = True print "duplicate found in %.2e tries in %f seconds" % (iterations, time.time()-start) print "The upper bound on this probability is %.2f %%" % (coll(iterations,upper_bound)*100) else: # If it's a new number, add it to the set of numbers checked already_found.add(item) iterations+=1 except KeyboardInterrupt: # If someone cancels the program midway - prints some statistics about the current progress total_time = time.time()-start print "Program cancelled - made %.2e attempts in %.4f seconds" % (iterations, total_time) print "The upper bound on getting a duplicate is %.2f %%" % (coll(iterations,upper_bound)*100) onepercent = ntimes(.01,upper_bound) rate = total_time/iterations seconds = onepercent*rate print "To have 1%% probability of guessing you need at least %d tries, at this rate it would take %f seconds" % (onepercent, seconds) print "%.2f minutes, %.2f hours, %.2f days, %.2f years" % (seconds/60, seconds/60/60, seconds/60/60/24, seconds/60/60/24/365)
def createUserSessionKey(org, username, sessionId, consistency=ConsistencyLevel.LOCAL_QUORUM, session=None): """ Create a session key record in the usersessionkeys table for the given user session :org: Name of organization for the user :username: Name of the user :sessionid: ID of the session to create a key for """ charList = (list(range(48, 58)) + # Numbers list(range(65, 91)) + # Uppercase list(range(97, 123))) # Lowercase sysrand = SystemRandom() sessionKey = ''.join( chr(sysrand.choice(charList)) for i in range(64)) try: createUserSessionKeyQuery = CassandraCluster.getPreparedStatement( """ INSERT INTO usersessionkeys ( sessionkey, org, username, sessionid ) VALUES ( ?, ?, ?, ? ) """, keyspace=session.keyspace) createUserSessionKeyQuery.consistency_level = consistency session.execute(createUserSessionKeyQuery, (sessionKey, org, username, sessionId)) return sessionKey except Exception as e: log.critical("Exception in AuthDB.createUserSessionKey: %s" % (e,))
def newAccount(): """ Create's a new account under this user. Balance is always 0 """ try: check_params(request, ["session", "pin"]) user = validate_session(request.form["session"]) except StandardError as e: return respond(str(e), code=400), 400 gen = SystemRandom() accnum = str(''.join(map(str, [gen.randrange(9) for i in range(10)]))) pin = int(request.form["pin"]) newaccount = Account(accnum, user, 0.00, pin) try: db.session.add(newaccount) db.session.commit() add_log(LOG_ACCOUNT, "User %s created a new account (%s)" % (user.username, accnum)) except: db.session.rollback() return respond("An internal error has occured. Please try again.", code=400), 400 # Delete their session delete_session(request.form["session"]) return respond("Account created!", data={'account': newaccount.id, 'pin': newaccount.pin})
def sign(self, message): """ Signs message using ECDSA. :param message: bytes to sign :return: bytes representing r, s. """ m = hashlib.sha256() m.update(message) e = m.digest() ln = self.sign_curve.order.bit_length() // 8 n = self.sign_curve.order z = e[0:ln] z = int.from_bytes(z, byteorder="big") # Matching the BigInteger form in the java signing. certificate = 0 while certificate == 0: rng = SystemRandom() k = rng.randint(1, n) kg = self.sign_curve.get_member(k) r = kg.x if r == 0: continue s = (mod_inv(k, n) * (z + (r * self.sign_key) % n) % n) % n if s == 0: continue l = [r, s] int_length = self.sign_curve.int_length // 8 certificate = list_to_bytes(l, int_length) return certificate
def directionsGenerator(steps): ''' generate unity steps in random directions ''' from random import SystemRandom from numpy import exp, pi s = SystemRandom() for i in xrange(steps): yield exp(s.random()*pi*2j)
def rand_ortho1(n): r = SystemRandom() pos = [r.random() for x in range(n)] s = sum(pos) v = array(pos,dtype=float)-(s/float(n)) norm = sqrt(sum(v*v)) return v/norm
def new_password(self, user, passhash): """ Return new random password """ chars = '23456qwertasdfgzxcvbQWERTASDFGZXCVB789yuiophjknmYUIPHJKLNM' r = SystemRandom() return ''.join(r.sample(chars, 8))
def throwAndSetRandomRun(source,runsAndProbs): """Pass a list of tuple pairs, with the first item of the pair a run number and the second number of the pair a weight. The function will normalize the weights so you do not have to worry about that. The pairs will be used to randomly choose what Run should be assigned to the job. """ from random import SystemRandom totalProb = 0. for r,p in runsAndProbs: totalProb+=p #this is the same random generator used to set the seeds for the RandomNumberGeneratorService random = SystemRandom() runProb = random.uniform(0,totalProb) sumProb = 0 runNumber = 0 for r,p in runsAndProbs: sumProb+=p if sumProb >= runProb: runNumber = r break print('setting runNumber to: ',runNumber) if source.type_() == "PoolSource": source.setRunNumber = cms.untracked.uint32(runNumber) else: #sources that inherit from ConfigurableInputSource use 'firstRun' source.firstRun = cms.untracked.uint32(runNumber) return
def populate(self, *excludePSets): """ _populate_ generate a bunch of seeds and stick them into this service This is the lazy user method. Optional args are names of PSets to *NOT* alter seeds. Eg: populate() will set all seeds populate("pset1", "pset2") will set all seeds but not those in psets named pset1 and pset2 """ import random from random import SystemRandom _inst = SystemRandom() _MAXINT = 900000000 # // # // count seeds and create the required number of seeds #// newSeeds = [ _inst.randint(1, _MAXINT) for i in range(self.countSeeds())] self._lockedSeeds = list(excludePSets) self.insertSeeds(*newSeeds) self._lockedSeeds = [] return
def test_stress(self): """ Runs a large number of threads doing operations with resources checked out, ensuring properties of the pool. """ rand = SystemRandom() n = rand.randint(1, 400) passes = rand.randint(1, 20) rounds = rand.randint(1, 200) breaker = rand.uniform(0, 1) pool = EmptyListPool() def _run(): for i in range(rounds): with pool.transaction() as a: self.assertEqual([], a) a.append(currentThread()) self.assertEqual([currentThread()], a) for p in range(passes): self.assertEqual([currentThread()], a) if rand.uniform(0, 1) > breaker: break a.remove(currentThread()) threads = [] for i in range(n): th = Thread(target=_run) threads.append(th) th.start() for th in threads: th.join()
def generate_salt(): # This uses os.urandom() underneath cryptogen = SystemRandom() # Create 16 byte hex salt salt_sequence = [cryptogen.randrange(256) for _ in range(16)] return ''.join([format(r, 'x') for r in salt_sequence])
def get_prime(low, high): csprng = SystemRandom() n = csprng.randrange(low, high) if n % 2 == 0: n += 1 while not miller_rabin(n): n += 2 return n
def __init__(self, length=16): rand = SystemRandom() rand_chars = rand.sample(RandomString.charsets,length) self.generated_string = "".join(rand_chars) m = hashlib.md5() m.update(self.generated_string) self.md5 = m.digest()
def tcp_scan(ips, ports, randomize=True): loop = asyncio.get_event_loop() if randomize: rdev = SystemRandom() ips = rdev.shuffle(ips) ports = rdev.shuffle(ports) tcp_Scanner_run(tcp_scanner(ip, port) for port in ports for ip in ips)
def encrypt(message,pubkey): ordnums = [ord(ch) for ch in message] p,a,akp = pubkey r1 = SystemRandom(time.time()) l = r1.randint(1,p-2) d = pow(a,l,p) encnums = [onum * pow(akp,l,p) for onum in ordnums] return (d,encnums)
def createRandomToken(self): '''Create a random byte sequence to use as a repeating token''' r = SystemRandom() token = bytearray() numBytes = r.choice([3, 4, 5, 6]) for i in range(numBytes): token.append(r.randrange(256)) return token
def rand_ortho1(n): from random import SystemRandom r = SystemRandom() pos = [r.random() for x in xrange(n)] s = sum(pos) v = array(pos,dtype=float)-(s/len(pos)) norm = sqrt(sum(v*v)) return v/norm
def cycle_app_reverse_cache(*args, **kwargs): """Does not really empty the cache; instead it adds a random element to the cache key generation which guarantees that the cache does not yet contain values for all newly generated keys""" cache.set('app_reverse_cache_generation', str(SystemRandom().random()))
from struct import Struct from random import SystemRandom from operator import xor from itertools import starmap from werkzeug._compat import range_type, PY2, text_type, izip, to_bytes, \ string_types, to_native SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' DEFAULT_PBKDF2_ITERATIONS = 1000 _pack_int = Struct('>I').pack _builtin_safe_str_cmp = getattr(hmac, 'compare_digest', None) _sys_rng = SystemRandom() _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, '/')) def _find_hashlib_algorithms(): algos = getattr(hashlib, 'algorithms', None) if algos is None: algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') rv = {} for algo in algos: func = getattr(hashlib, algo, None) if func is not None: rv[algo] = func return rv _hash_funcs = _find_hashlib_algorithms()
# Schnorr signature built using: # Elliptic Curve Cryptography using the BitCoin curve, SECG secp256k1 # This version uses the X,Y,Z "Jacobi coordinates" representation, for speed # Dr. Orion Lawlor, [email protected], 2015-03-25 (Public Domain) from hashlib import sha256 from random import SystemRandom # cryptographic random byte generator #from Oracle import Oracle rand = SystemRandom() # create strong random number generator def hex2int(hexString): return int("".join(hexString.replace(":", "").split()), 16) # Half the extended Euclidean algorithm: # Computes gcd(a,b) = a*x + b*y # Returns only gcd, x (not y) # From http://rosettacode.org/wiki/Modular_inverse#Python def half_extended_gcd(aa, bb): lastrem, rem = abs(aa), abs(bb) x, lastx = 0, 1 while rem: lastrem, (quotient, rem) = rem, divmod(lastrem, rem) x, lastx = lastx - quotient * x, x return lastrem, lastx # Modular inverse: compute the multiplicative inverse i of a mod m: # i*a = a*i = 1 mod m def modular_inverse(a, m):
global data_dir data_dir = 'data/' form = cgi.FieldStorage() # A nested FieldStorage instance holds the file fileitem = form['fastafile'] # Test if the file was uploaded #message = "oops" #message = str(form) message = '' global run_name run_name = ''.join(SystemRandom().choice(ascii_uppercase + digits) for _ in range(6)) while os.path.isfile(run_name): run_name = ''.join(SystemRandom().choice(ascii_uppercase + digits) for _ in range(6)) #writes a sequence or sequence file to the data directory def write_sequence(sequence, sequence_filename): fasta_filename = data_dir + run_name if sequence != '': if check_fasta(sequence, 'nucleotide', false): fasta_file = open(fasta_filename) sequence = clean_sequence(sequence) fasta_file.write(sequence)
def __init__(self, configuration=None, name=None): SimpleService.__init__(self, configuration=configuration, name=name) self.order = ORDER self.definitions = CHARTS self.random = SystemRandom()
from app.scrum.prod import prod app.register_blueprint(prod) from app.scrum.mast import mast app.register_blueprint(mast) from app.scrum.dev import dev app.register_blueprint(dev) from app.scrum.actor import actor app.register_blueprint(actor) from app.scrum.objetivo import objetivo app.register_blueprint(objetivo) from app.scrum.accion import accion app.register_blueprint(accion) from app.scrum.historias import historias app.register_blueprint(historias) from app.scrum.tareas import tareas app.register_blueprint(tareas) from app.scrum.cates import cates app.register_blueprint(cates) if __name__ == '__main__': app.config.update(SECRET_KEY=repr(SystemRandom().random())) manager.run()
def genpass(length=32, special="_-#|+="): """generates a password with random chararcters """ chars = special + string.ascii_letters + string.digits + " " return "".join(SystemRandom().choice(chars) for _ in range(length))
import json np.set_printoptions(threshold=np.inf) def unwrap_self_pairs(arg, **kwarg): """ Helper function for multiprocessing :param arg: :param kwarg: :return: """ return KeyReader.chitext_creation_process(*arg, **kwarg) gen = SystemRandom() def generate_plaintext(length): """ Generieren von Klartext als liste :param length: :return: """ # return [1, 0, 1, 0, 0] # For testing purposes # return np.asarray([randint(0, 1) for x in xrange(length)]) return np.asarray([gen.randrange(2) for x in xrange(length)]) class KeyReader: """
from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from random import SystemRandom # Signing authority (SA) key priv = RSA.generate(3072) pub = priv.publickey() ## Protocol: Blind signature ## # must be guaranteed to be chosen uniformly at random r = SystemRandom().randrange(pub.n >> 10, pub.n) msg = 'OStoLFQC' # large message (larger than the modulus) msg = str.encode(msg) # hash message so that messages of arbitrary length can be signed hash = SHA256.new() hash.update(msg) msgDigest = hash.digest() # user computes msg_blinded = pub.blind(msgDigest, r) # SA computes msg_blinded_signature = priv.sign(msg_blinded, 0) # user computes msg_signature = pub.unblind(msg_blinded_signature[0], r) print('----msg_signature---------')
class Interest(object): def __init__(self, value=None): if isinstance(value, Interest): # Copy the values. self._name = ChangeCounter(Name(value.getName())) self._minSuffixComponents = value._minSuffixComponents self._maxSuffixComponents = value._maxSuffixComponents self._keyLocator = ChangeCounter(KeyLocator(value.getKeyLocator())) self._exclude = ChangeCounter(Exclude(value.getExclude())) self._childSelector = value._childSelector self._mustBeFresh = value._mustBeFresh self._nonce = value.getNonce() self._interestLifetimeMilliseconds = value._interestLifetimeMilliseconds self._forwardingHint = ChangeCounter( DelegationSet(value.getForwardingHint())) self._linkWireEncoding = value._linkWireEncoding self._linkWireEncodingFormat = value._linkWireEncodingFormat self._link = ChangeCounter(None) if value._link.get() != None: self._link.set(Link(value._link.get())) self._selectedDelegationIndex = value._selectedDelegationIndex self._defaultWireEncoding = value.getDefaultWireEncoding() self._defaultWireEncodingFormat = value._defaultWireEncodingFormat else: self._name = ChangeCounter( Name(value) if isinstance(value, Name) else Name()) self._minSuffixComponents = None self._maxSuffixComponents = None self._keyLocator = ChangeCounter(KeyLocator()) self._exclude = ChangeCounter(Exclude()) self._childSelector = None self._mustBeFresh = True self._nonce = Blob() self._interestLifetimeMilliseconds = None self._forwardingHint = ChangeCounter(DelegationSet()) self._linkWireEncoding = Blob() self._linkWireEncodingFormat = None self._link = ChangeCounter(None) self._selectedDelegationIndex = None self._defaultWireEncoding = SignedBlob() self._defaultWireEncodingFormat = None self._getNonceChangeCount = 0 self._getDefaultWireEncodingChangeCount = 0 self._changeCount = 0 self._lpPacket = None def getName(self): """ Get the interest Name. :return: The name. The name size() may be 0 if not specified. :rtype: Name """ return self._name.get() def getMinSuffixComponents(self): """ Get the min suffix components. :return: The min suffix components, or None if not specified. :rtype: int """ return self._minSuffixComponents def getMaxSuffixComponents(self): """ Get the max suffix components. :return: The max suffix components, or None if not specified. :rtype: int """ return self._maxSuffixComponents def getKeyLocator(self): """ Get the interest key locator. :return: The key locator. If getType() is None, then the key locator is not specified. :rtype: KeyLocator """ return self._keyLocator.get() def getExclude(self): """ Get the exclude object. :return: The exclude object. If the exclude size() is zero, then the exclude is not specified. :rtype: Exclude """ return self._exclude.get() def getChildSelector(self): """ Get the child selector. :return: The child selector, or None if not specified. :rtype: int """ return self._childSelector def getMustBeFresh(self): """ Get the must be fresh flag. :return: The must be fresh flag. If not specified, the default is True. :rtype: bool """ return self._mustBeFresh def getNonce(self): """ Return the nonce value from the incoming interest. If you change any of the fields in this Interest object, then the nonce value is cleared. :return: The nonce. If isNull() then the nonce is omitted. :rtype: Blob """ if self._getNonceChangeCount != self.getChangeCount(): # The values have changed, so the existing nonce is invalidated. self._nonce = Blob() self._getNonceChangeCount = self.getChangeCount() return self._nonce def getForwardingHint(self): """ Get the forwarding hint object which you can modify to add or remove forwarding hints. :return: The forwarding hint as a DelegationSet. :rtype: DelegationSet """ return self._forwardingHint.get() def hasLink(self): """ Check if this interest has a link object (or a link wire encoding which can be decoded to make the link object). :return: True if this interest has a link object, False if not. :rtype: bool :deprecated: Use getForwardingHint. """ return self._link.get() != None or not self._linkWireEncoding.isNull() def getLink(self): """ Get the link object. If necessary, decode it from the link wire encoding. :return: The link object, or None if not specified. :rtype: Link :raises ValueError: For error decoding the link wire encoding (if necessary). :deprecated: Use getForwardingHint. """ if self._link.get() != None: return self._link.get() elif not self._linkWireEncoding.isNull(): # Decode the link object from linkWireEncoding_. link = Link() link.wireDecode(self._linkWireEncoding, self._linkWireEncodingFormat) self._link.set(link) # Clear _linkWireEncoding since it is now managed by the link object. self._linkWireEncoding = Blob() self._linkWireEncodingFormat = None return link else: return None def getLinkWireEncoding(self, wireFormat=None): """ Get the wire encoding of the link object. If there is already a wire encoding then return it. Otherwise encode from the link object (if available). :param WireFormat wireFormat: (optional) A WireFormat object used to encode the Link. If omitted, use WireFormat.getDefaultWireFormat(). :return: The wire encoding, or an isNull Blob if the link is not specified. :rtype: Blob :deprecated: Use getForwardingHint. """ if wireFormat == None: # Don't use a default argument since getDefaultWireFormat can change. wireFormat = WireFormat.getDefaultWireFormat() if (not self._linkWireEncoding.isNull() and self._linkWireEncodingFormat == wireFormat): return self._linkWireEncoding link = self.getLink() if link != None: return link.wireEncode(wireFormat) else: return Blob() def getSelectedDelegationIndex(self): """ Get the selected delegation index. :return: The selected delegation index. If not specified, return None. :rtype: int :deprecated: Use getForwardingHint. """ return self._selectedDelegationIndex def getInterestLifetimeMilliseconds(self): """ Get the interest lifetime. :return: The interest lifetime in milliseconds, or None if not specified. :rtype: float """ return self._interestLifetimeMilliseconds def getIncomingFaceId(self): """ Get the incoming face ID according to the incoming packet header. :return: The incoming face ID. If not specified, return None. :rtype: int """ field = (None if self._lpPacket == None else IncomingFaceId.getFirstHeader(self._lpPacket)) return None if field == None else field.getFaceId() def setName(self, name): """ Set the interest name. :note: You can also call getName and change the name values directly. :param Name name: The interest name. This makes a copy of the name. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._name.set(name if isinstance(name, Name) else Name(name)) self._changeCount += 1 return self def setMinSuffixComponents(self, minSuffixComponents): """ Set the min suffix components count. :param int minSuffixComponents: The min suffix components count. If not specified, set to None. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._minSuffixComponents = Common.nonNegativeIntOrNone( minSuffixComponents) self._changeCount += 1 return self def setMaxSuffixComponents(self, maxSuffixComponents): """ Set the max suffix components count. :param int maxSuffixComponents: The max suffix components count. If not specified, set to None. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._maxSuffixComponents = Common.nonNegativeIntOrNone( maxSuffixComponents) self._changeCount += 1 return self def setKeyLocator(self, keyLocator): """ Set this interest to use a copy of the given KeyLocator object. :note: You can also call getKeyLocator and change the key locator directly. :param KeyLocator keyLocator: The KeyLocator object. This makes a copy of the object. If no key locator is specified, set to a new default KeyLocator(), or to a KeyLocator with an unspecified type. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._keyLocator.set( KeyLocator(keyLocator) if isinstance(keyLocator, KeyLocator ) else KeyLocator()) self._changeCount += 1 return self def setExclude(self, exclude): """ Set this interest to use a copy of the given Exclude object. :note: You can also call getExclude and change the exclude entries directly. :param Exclude exclude: The Exclude object. This makes a copy of the object. If no exclude is specified, set to a new default Exclude(), or to an Exclude with size() 0. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._exclude.set( Exclude(exclude) if isinstance(exclude, Exclude) else Exclude()) self._changeCount += 1 return self def setForwardingHint(self, forwardingHint): """ Set this interest to use a copy of the given DelegationSet object as the forwarding hint. :note: You can also call getForwardingHint and change the forwarding hint directly. :param DelegationSet forwardingHint: The DelegationSet object to use as the forwarding hint. This makes a copy of the object. If no forwarding hint is specified, set to a new default DelegationSet() with no entries. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._forwardingHint.set( DelegationSet(forwardingHint) if isinstance( forwardingHint, DelegationSet) else DelegationSet()) self._changeCount += 1 return self def setLinkWireEncoding(self, encoding, wireFormat=None): """ Set the link wire encoding bytes, without decoding them. If there is a link object, set it to None. If you later call getLink(), it will decode the wireEncoding to create the link object. :param Blob encoding: The Blob with the bytes of the link wire encoding. If no link is specified, set to an empty Blob() or call unsetLink(). :param WireFormat wireFormat: The wire format of the encoding, to be used later if necessary to decode. If omitted, use WireFormat.getDefaultWireFormat(). :return: This Interest so that you can chain calls to update values. :rtype: Interest :deprecated: Use setForwardingHint. """ if wireFormat == None: # Don't use a default argument since getDefaultWireFormat can change. wireFormat = WireFormat.getDefaultWireFormat() self._linkWireEncoding = encoding self._linkWireEncodingFormat = wireFormat # Clear the link object, assuming that it has a different encoding. self._link.set(None) self._changeCount += 1 return self def unsetLink(self): """ Clear the link wire encoding and link object so that getLink() returns None. :return: This Interest so that you can chain calls to update values. :rtype: Interest :deprecated: Use setForwardingHint. """ return self.setLinkWireEncoding(Blob(), None) def setSelectedDelegationIndex(self, selectedDelegationIndex): """ Set the selected delegation index. :param int selectedDelegationIndex: The selected delegation index. If not specified, set to None. :return: This Interest so that you can chain calls to update values. :rtype: Interest :deprecated: Use setForwardingHint. """ self._selectedDelegationIndex = Common.nonNegativeIntOrNone( selectedDelegationIndex) self._changeCount += 1 return self def setChildSelector(self, childSelector): """ Set the child selector. :param int childSelector: The child selector. If not specified, set to None. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._childSelector = Common.nonNegativeIntOrNone(childSelector) self._changeCount += 1 return self def setMustBeFresh(self, mustBeFresh): """ Set the MustBeFresh flag. :param bool mustBeFresh: True if the content must be fresh, otherwise False. If you do not set this flag, the default value is true. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._mustBeFresh = True if mustBeFresh else False self._changeCount += 1 return self def setNonce(self, nonce): """ :deprecated: You should let the wire encoder generate a random nonce internally before sending the interest. """ self._nonce = nonce if isinstance(nonce, Blob) else Blob(nonce) # Set _getNonceChangeCount so that the next call to getNonce() won't # clear _nonce. self._changeCount += 1 self._getNonceChangeCount = self.getChangeCount() return self def setInterestLifetimeMilliseconds(self, interestLifetimeMilliseconds): """ Set the interest lifetime. :param float interestLifetimeMilliseconds: The interest lifetime in milliseconds. If not specified, set to None. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._interestLifetimeMilliseconds = Common.nonNegativeFloatOrNone( interestLifetimeMilliseconds) self._changeCount += 1 return self def wireEncode(self, wireFormat=None): """ Encode this Interest for a particular wire format. If wireFormat is the default wire format, also set the defaultWireEncoding field to the encoded result. :param wireFormat: (optional) A WireFormat object used to encode this Interest. If omitted, use WireFormat.getDefaultWireFormat(). :type wireFormat: A subclass of WireFormat :return: The encoded buffer. :rtype: SignedBlob """ if wireFormat == None: # Don't use a default argument since getDefaultWireFormat can change. wireFormat = WireFormat.getDefaultWireFormat() if (not self.getDefaultWireEncoding().isNull() and self.getDefaultWireEncodingFormat() == wireFormat): # We already have an encoding in the desired format. return self.getDefaultWireEncoding() (encoding, signedPortionBeginOffset, signedPortionEndOffset) = \ wireFormat.encodeInterest(self) wireEncoding = SignedBlob(encoding, signedPortionBeginOffset, signedPortionEndOffset) if wireFormat == WireFormat.getDefaultWireFormat(): # This is the default wire encoding. self._setDefaultWireEncoding(wireEncoding, WireFormat.getDefaultWireFormat()) return wireEncoding def wireDecode(self, input, wireFormat=None): """ Decode the input using a particular wire format and update this Interest. If wireFormat is the default wire format, also set the defaultWireEncoding to another pointer to the input. :param input: The array with the bytes to decode. If input is not a Blob, then copy the bytes to save the defaultWireEncoding (otherwise take another pointer to the same Blob). :type input: A Blob or an array type with int elements :param wireFormat: (optional) A WireFormat object used to decode this Interest. If omitted, use WireFormat.getDefaultWireFormat(). :type wireFormat: A subclass of WireFormat """ if wireFormat == None: # Don't use a default argument since getDefaultWireFormat can change. wireFormat = WireFormat.getDefaultWireFormat() if isinstance(input, Blob): # Input is a blob, so get its buf() and set copy False. result = wireFormat.decodeInterest(self, input.buf(), False) else: result = wireFormat.decodeInterest(self, input, True) (signedPortionBeginOffset, signedPortionEndOffset) = result if wireFormat == WireFormat.getDefaultWireFormat(): # This is the default wire encoding. In the Blob constructor, set # copy true, but if input is already a Blob, it won't copy. self._setDefaultWireEncoding( SignedBlob(Blob(input, True), signedPortionBeginOffset, signedPortionEndOffset), WireFormat.getDefaultWireFormat()) else: self._setDefaultWireEncoding(SignedBlob(), None) def toUri(self): """ Encode the name according to the "NDN URI Scheme". If there are interest selectors, append "?" and add the selectors as a query string. For example "/test/name?ndn.ChildSelector=1". :note: This is an experimental feature. See the API docs for more detail at http://named-data.net/doc/ndn-ccl-api/interest.html#interest-touri-method . :return: The URI string. :rtype: string """ selectors = "" if self._minSuffixComponents != None: selectors += "&ndn.MinSuffixComponents=" + repr( self._minSuffixComponents) if self._maxSuffixComponents != None: selectors += "&ndn.MaxSuffixComponents=" + repr( self._maxSuffixComponents) if self._childSelector != None: selectors += "&ndn.ChildSelector=" + repr(self._childSelector) if self._mustBeFresh: selectors += "&ndn.MustBeFresh=true" if self._interestLifetimeMilliseconds != None: selectors += "&ndn.InterestLifetime=" + repr( int(round(self._interestLifetimeMilliseconds))) if self.getNonce().size() > 0: selectors += ("&ndn.Nonce=" + Name.toEscapedString(self.getNonce().buf())) if self.getExclude().size() > 0: selectors += "&ndn.Exclude=" + self.getExclude().toUri() result = self.getName().toUri() if selectors != "": # Replace the first & with ?. result += "?" + selectors[1:] return result def refreshNonce(self): """ Update the bytes of the nonce with new random values. This ensures that the new nonce value is different than the current one. If the current nonce is not specified, this does nothing. """ currentNonce = self.getNonce() if currentNonce.size() == 0: return while True: value = bytearray(currentNonce.size()) for i in range(len(value)): value[i] = self._systemRandom.randint(0, 0xff) newNonce = Blob(value, False) if newNonce != currentNonce: break self._nonce = newNonce # Set _getNonceChangeCount so that the next call to getNonce() won't # clear _nonce. self._changeCount += 1 self._getNonceChangeCount = self.getChangeCount() def matchesName(self, name): """ Check if this interest's name matches the given name (using Name.match) and the given name also conforms to the interest selectors. :param Name name: The name to check. :return: True if the name and interest selectors match, False otherwise. :rtype: bool """ if not self.getName().match(name): return False if (self._minSuffixComponents != None and # Add 1 for the implicit digest. not (name.size() + 1 - self.getName().size() >= self._minSuffixComponents)): return False if (self._maxSuffixComponents != None and # Add 1 for the implicit digest. not (name.size() + 1 - self.getName().size() <= self._maxSuffixComponents)): return False if (self.getExclude().size() > 0 and name.size() > self.getName().size() and self.getExclude().matches(name[self.getName().size()])): return False return True def matchesData(self, data, wireFormat=None): """ Check if the given Data packet can satisfy this Interest. This method considers the Name, MinSuffixComponents, MaxSuffixComponents, PublisherPublicKeyLocator, and Exclude. It does not consider the ChildSelector or MustBeFresh. This uses the given wireFormat to get the Data packet encoding for the full Name. :param Data data: The Data packet to check. :param wireFormat: (optional) A WireFormat object used to encode the Data packet to get its full Name. If omitted, use WireFormat.getDefaultWireFormat(). :type wireFormat: A subclass of WireFormat :return: True if the given Data packet can satisfy this Interest. :rtype: bool """ # Imitate ndn-cxx Interest::matchesData. interestNameLength = self.getName().size() dataName = data.getName() fullNameLength = dataName.size() + 1 # Check MinSuffixComponents. hasMinSuffixComponents = (self.getMinSuffixComponents() != None) minSuffixComponents = (self.getMinSuffixComponents() if hasMinSuffixComponents else 0) if not (interestNameLength + minSuffixComponents <= fullNameLength): return False # Check MaxSuffixComponents. hasMaxSuffixComponents = (self.getMaxSuffixComponents() != None) if (hasMaxSuffixComponents and not (interestNameLength + self.getMaxSuffixComponents() >= fullNameLength)): return False # Check the prefix. if interestNameLength == fullNameLength: if self.getName().get(-1).isImplicitSha256Digest(): if not self.getName().equals(data.getFullName(wireFormat)): return False else: # The Interest Name is the same length as the Data full Name, # but the last component isn't a digest so there's no # possibility of matching. return False else: # The Interest Name should be a strict prefix of the Data full Name. if not self.getName().isPrefixOf(dataName): return False # Check the Exclude. # The Exclude won't be violated if the Interest Name is the same as the # Data full Name. if self.getExclude().size( ) > 0 and fullNameLength > interestNameLength: if interestNameLength == fullNameLength - 1: # The component to exclude is the digest. if self.getExclude().matches( data.getFullName(wireFormat).get(interestNameLength)): return False else: # The component to exclude is not the digest. if self.getExclude().matches(dataName.get(interestNameLength)): return False # Check the KeyLocator. publisherPublicKeyLocator = self.getKeyLocator() if publisherPublicKeyLocator.getType() != None: signature = data.getSignature() if not KeyLocator.canGetFromSignature(signature): # No KeyLocator in the Data packet. return False if not publisherPublicKeyLocator.equals( (KeyLocator.getFromSignature(signature))): return False return True def getDefaultWireEncoding(self): """ Return the default wire encoding, which was encoded with getDefaultWireEncodingFormat(). :return: The default wire encoding, whose isNull() may be true if there is no default wire encoding. :rtype: SignedBlob """ if self._getDefaultWireEncodingChangeCount != self.getChangeCount(): # The values have changed, so the default wire encoding is # invalidated. self._defaultWireEncoding = SignedBlob() self._defaultWireEncodingFormat = None self._getDefaultWireEncodingChangeCount = self.getChangeCount() return self._defaultWireEncoding def getDefaultWireEncodingFormat(self): """ Get the WireFormat which is used by getDefaultWireEncoding(). :return: The WireFormat, which is only meaningful if the getDefaultWireEncoding() is not isNull(). :rtype: WireFormat """ return self._defaultWireEncodingFormat def setLpPacket(self, lpPacket): """ An internal library method to set the LpPacket for an incoming packet. The application should not call this. :param LpPacket lpPacket: The LpPacket. This does not make a copy. :return: This Interest so that you can chain calls to update values. :rtype: Interest :note: This is an experimental feature. This API may change in the future. """ self._lpPacket = lpPacket # Don't update _changeCount since this doesn't affect the wire encoding. return self def getChangeCount(self): """ Get the change count, which is incremented each time this object (or a child object) is changed. :return: The change count. :rtype: int """ # Make sure each of the checkChanged is called. changed = self._name.checkChanged() changed = self._keyLocator.checkChanged() or changed changed = self._exclude.checkChanged() or changed changed = self._forwardingHint.checkChanged() or changed if changed: # A child object has changed, so update the change count. self._changeCount += 1 return self._changeCount def _setDefaultWireEncoding(self, defaultWireEncoding, defaultWireEncodingFormat): self._defaultWireEncoding = defaultWireEncoding self._defaultWireEncodingFormat = defaultWireEncodingFormat # Set _getDefaultWireEncodingChangeCount so that the next call to # getDefaultWireEncoding() won't clear _defaultWireEncoding. self._getDefaultWireEncodingChangeCount = self.getChangeCount() _systemRandom = SystemRandom() # Create managed properties for read/write properties of the class for more pythonic syntax. name = property(getName, setName) minSuffixComponents = property(getMinSuffixComponents, setMinSuffixComponents) maxSuffixComponents = property(getMaxSuffixComponents, setMaxSuffixComponents) keyLocator = property(getKeyLocator, setKeyLocator) exclude = property(getExclude, setExclude) childSelector = property(getChildSelector, setChildSelector) mustBeFresh = property(getMustBeFresh, setMustBeFresh) nonce = property(getNonce, setNonce) interestLifetimeMilliseconds = property(getInterestLifetimeMilliseconds, setInterestLifetimeMilliseconds)
class ObjectId(object): """A MongoDB ObjectId. """ _pid = os.getpid() _inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE) _inc_lock = threading.Lock() __random = _random_bytes() __slots__ = ('__id', ) _type_marker = 7 def __init__(self, oid=None): """Initialize a new ObjectId. An ObjectId is a 12-byte unique identifier consisting of: - a 4-byte value representing the seconds since the Unix epoch, - a 5-byte random value, - a 3-byte counter, starting with a random value. By default, ``ObjectId()`` creates a new unique identifier. The optional parameter `oid` can be an :class:`ObjectId`, or any 12 :class:`bytes` or, in Python 2, any 12-character :class:`str`. For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId specification but they are acceptable input:: >>> ObjectId(b'foo-bar-quux') ObjectId('666f6f2d6261722d71757578') `oid` can also be a :class:`unicode` or :class:`str` of 24 hex digits:: >>> ObjectId('0123456789ab0123456789ab') ObjectId('0123456789ab0123456789ab') >>> >>> # A u-prefixed unicode literal: >>> ObjectId(u'0123456789ab0123456789ab') ObjectId('0123456789ab0123456789ab') Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor 24 hex digits, or :class:`TypeError` if `oid` is not an accepted type. :Parameters: - `oid` (optional): a valid ObjectId. .. mongodoc:: objectids .. versionchanged:: 3.8 :class:`~bson.objectid.ObjectId` now implements the `ObjectID specification version 0.2 <https://github.com/mongodb/specifications/blob/master/source/ objectid.rst>`_. """ if oid is None: self.__generate() elif isinstance(oid, bytes) and len(oid) == 12: self.__id = oid else: self.__validate(oid) @classmethod def from_datetime(cls, generation_time): """Create a dummy ObjectId instance with a specific generation time. This method is useful for doing range queries on a field containing :class:`ObjectId` instances. .. warning:: It is not safe to insert a document containing an ObjectId generated using this method. This method deliberately eliminates the uniqueness guarantee that ObjectIds generally provide. ObjectIds generated with this method should be used exclusively in queries. `generation_time` will be converted to UTC. Naive datetime instances will be treated as though they already contain UTC. An example using this helper to get documents where ``"_id"`` was generated before January 1, 2010 would be: >>> gen_time = datetime.datetime(2010, 1, 1) >>> dummy_id = ObjectId.from_datetime(gen_time) >>> result = collection.find({"_id": {"$lt": dummy_id}}) :Parameters: - `generation_time`: :class:`~datetime.datetime` to be used as the generation time for the resulting ObjectId. """ if generation_time.utcoffset() is not None: generation_time = generation_time - generation_time.utcoffset() timestamp = calendar.timegm(generation_time.timetuple()) oid = struct.pack(">I", int(timestamp)) + b"\x00\x00\x00\x00\x00\x00\x00\x00" return cls(oid) @classmethod def is_valid(cls, oid): """Checks if a `oid` string is valid or not. :Parameters: - `oid`: the object id to validate .. versionadded:: 2.3 """ if not oid: return False try: ObjectId(oid) return True except (InvalidId, TypeError): return False @classmethod def _random(cls): """Generate a 5-byte random number once per process. """ pid = os.getpid() if pid != cls._pid: cls._pid = pid cls.__random = _random_bytes() return cls.__random def __generate(self): """Generate a new value for this ObjectId. """ # 4 bytes current time oid = struct.pack(">I", int(time.time())) # 5 bytes random oid += ObjectId._random() # 3 bytes inc with ObjectId._inc_lock: oid += struct.pack(">I", ObjectId._inc)[1:4] ObjectId._inc = (ObjectId._inc + 1) % (_MAX_COUNTER_VALUE + 1) self.__id = oid def __validate(self, oid): """Validate and use the given id for this ObjectId. Raises TypeError if id is not an instance of (:class:`basestring` (:class:`str` or :class:`bytes` in python 3), ObjectId) and InvalidId if it is not a valid ObjectId. :Parameters: - `oid`: a valid ObjectId """ if isinstance(oid, ObjectId): self.__id = oid.binary # bytes or unicode in python 2, str in python 3 elif isinstance(oid, string_type): if len(oid) == 24: try: self.__id = bytes_from_hex(oid) except (TypeError, ValueError): _raise_invalid_id(oid) else: _raise_invalid_id(oid) else: raise TypeError("id must be an instance of (bytes, %s, ObjectId), " "not %s" % (text_type.__name__, type(oid))) @property def binary(self): """12-byte binary representation of this ObjectId. """ return self.__id @property def generation_time(self): """A :class:`datetime.datetime` instance representing the time of generation for this :class:`ObjectId`. The :class:`datetime.datetime` is timezone aware, and represents the generation time in UTC. It is precise to the second. """ timestamp = struct.unpack(">I", self.__id[0:4])[0] return datetime.datetime.fromtimestamp(timestamp, utc) def __getstate__(self): """return value of object for pickling. needed explicitly because __slots__() defined. """ return self.__id def __setstate__(self, value): """explicit state set from pickling """ # Provide backwards compatability with OIDs # pickled with pymongo-1.9 or older. if isinstance(value, dict): oid = value["_ObjectId__id"] else: oid = value # ObjectIds pickled in python 2.x used `str` for __id. # In python 3.x this has to be converted to `bytes` # by encoding latin-1. if PY3 and isinstance(oid, text_type): self.__id = oid.encode('latin-1') else: self.__id = oid def __str__(self): if PY3: return binascii.hexlify(self.__id).decode() return binascii.hexlify(self.__id) def __repr__(self): return "ObjectId('%s')" % (str(self), ) def __eq__(self, other): if isinstance(other, ObjectId): return self.__id == other.binary return NotImplemented def __ne__(self, other): if isinstance(other, ObjectId): return self.__id != other.binary return NotImplemented def __lt__(self, other): if isinstance(other, ObjectId): return self.__id < other.binary return NotImplemented def __le__(self, other): if isinstance(other, ObjectId): return self.__id <= other.binary return NotImplemented def __gt__(self, other): if isinstance(other, ObjectId): return self.__id > other.binary return NotImplemented def __ge__(self, other): if isinstance(other, ObjectId): return self.__id >= other.binary return NotImplemented def __hash__(self): """Get a hash value for this :class:`ObjectId`.""" return hash(self.__id)
SUPPORT_SEEK, SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) _RND = SystemRandom() ENTITY_ID_FORMAT = DOMAIN + ".{}" ENTITY_IMAGE_URL = "/api/media_player_proxy/{0}?token={1}&cache={2}" CACHE_IMAGES = "images" CACHE_MAXSIZE = "maxsize" CACHE_LOCK = "lock" CACHE_URL = "url" CACHE_CONTENT = "content" ENTITY_IMAGE_CACHE = { CACHE_IMAGES: collections.OrderedDict(), CACHE_MAXSIZE: 16 } SCAN_INTERVAL = timedelta(seconds=10)
def _random_bytes(): """Get the 5-byte random field of an ObjectId.""" return struct.pack(">Q", SystemRandom().randint(0, 0xFFFFFFFFFF))[3:]
import hashlib import sys import os from random import SystemRandom import base64 import hmac if len(sys.argv) < 2: sys.stderr.write('Please include username as an argument.\n') sys.exit(0) username = sys.argv[1] #This uses os.urandom() underneath cryptogen = SystemRandom() #Create 16 byte hex salt salt_sequence = [cryptogen.randrange(256) for i in range(16)] hexseq = list(map(hex, salt_sequence)) salt = "".join([x[2:] for x in hexseq]) #Create 32 byte b64 password password = base64.urlsafe_b64encode(os.urandom(32)) digestmod = hashlib.sha256 if sys.version_info.major >= 3: password = password.decode('utf-8') digestmod = 'SHA256'
""" Welborn Productions - Utilities - ID Tools Tools that any model can use to generate unique ids. These are not safe-guarded ids. -Christopher Welborn 2-2-15 """ from random import SystemRandom SYSRANDOM = SystemRandom() # Changing the start char will wreck previously encoded ids. IDSTARTCHAR = 'a' # IDPADCHARS cannot contain IDSTARTCHAR + 9 letters (a -> j, when 'a' is used) IDPADCHARS = 'lmnopqrstuvwxyz' def encode_id(realid, length=4): """ A form of encoding that is reversible. Ensures an id at least `length` + `length // 2` characters long. Example: encode_id(123, length=4) 'btycydx' Arguments: realid : Int or digit string to encode. length : Max length for the actual id. Automatically bumped up to len(str(realid)) when needed. """ realidstr = str(realid) if not realidstr.isdigit(): raise ValueError( 'Expecting a number, or str of digits. Got: ({}) {!r}'.format(
import os from random import SystemRandom import ntpath import PySimpleGUI as sg from PIL import Image, ImageDraw _random = SystemRandom() def merge_images(img1, img2, output_path=os.getcwd()): img_A = Image.open(img1) img_B = Image.open(img2) head, tail = ntpath.split("Merge_res.png") file_name_AB = tail or ntpath.basename(head) img_A.paste(img_B, (0, 0), img_B) img_A.save(output_path + '\\' + file_name_AB, 'PNG') sg.popup('Done!') def visual_crypto(file_path, output_path=os.getcwd()): img = Image.open(file_path) f, e = os.path.splitext(file_path) out_filename_A = f + "_A.png" out_filename_B = f + "_B.png" out_filename_AB = f + "_AB_res.png" img = img.convert('1') # convert image to 1 bit # Prepare two empty slider images for drawing
def so_random(self, x, y): return SystemRandom().randint(x, y)
ON_OFF = 1 STREAM = 2 # These SUPPORT_* constants are deprecated as of Home Assistant 2022.5. # Pleease use the CameraEntityFeature enum instead. SUPPORT_ON_OFF: Final = 1 SUPPORT_STREAM: Final = 2 RTSP_PREFIXES = {"rtsp://", "rtsps://"} DEFAULT_CONTENT_TYPE: Final = "image/jpeg" ENTITY_IMAGE_URL: Final = "/api/camera_proxy/{0}?token={1}" TOKEN_CHANGE_INTERVAL: Final = timedelta(minutes=5) _RND: Final = SystemRandom() MIN_STREAM_INTERVAL: Final = 0.5 # seconds CAMERA_SERVICE_SNAPSHOT: Final = {vol.Required(ATTR_FILENAME): cv.template} CAMERA_SERVICE_PLAY_STREAM: Final = { vol.Required(ATTR_MEDIA_PLAYER): cv.entities_domain(DOMAIN_MP), vol.Optional(ATTR_FORMAT, default="hls"): vol.In(OUTPUT_FORMATS), } CAMERA_SERVICE_RECORD: Final = { vol.Required(CONF_FILENAME): cv.template, vol.Optional(CONF_DURATION, default=30): vol.Coerce(int), vol.Optional(CONF_LOOKBACK, default=0): vol.Coerce(int), }
to_output = motion.reshape(-1, FLAGS.frame_size) else: to_output = motion np.savetxt(fp, to_output, delimiter=",") print("Motion was written to " + file_name) if __name__ == '__main__': torch.manual_seed(args.random_seed) np.random.seed(args.random_seed) experimentID = args.load if experimentID is None: # Make a new experiment ID experimentID = int(SystemRandom().random()*100000) ckpt_path = os.path.join(args.save, "experiment_" + str(experimentID) + '.ckpt') start = time.time() print("Sampling dataset of {} training examples".format(args.n)) input_command = sys.argv ind = [i for i in range(len(input_command)) if input_command[i] == "--load"] if len(ind) == 1: ind = ind[0] input_command = input_command[:ind] + input_command[(ind+2):] input_command = " ".join(input_command) utils.makedirs("results/") ##################################################################
def bsidh_main(ctx): algo = ctx.meta['sidh.kwargs']['algo'] setting = ctx.meta['sidh.kwargs'] curve = algo.curve tuned_name = ('-classical', '-suitable')[setting.tuned] SIDp = algo.curve.SIDp SIDm = algo.curve.SIDm SQR, ADD = algo.curve.SQR, algo.curve.ADD p = algo.params.p global_L = algo.curve.L coeff = curve.coeff random = SystemRandom() fp = curve.fp f_name = 'data/strategies/' + setting.algorithm + '-' + setting.prime + '-' + algo.formula.name + tuned_name try: f = open(resource_filename('sidh', f_name)) print("// Strategies to be read from a file") # Corresponding to the list of Small Isogeny Degree, Lp := [l_0, ..., # l_{n-1}] [We need to include case l=2 and l=4] tmp = f.readline() tmp = [int(b) for b in tmp.split()] Sp = list(tmp) # Corresponding to the list of Small Isogeny Degree, Lm := [l_0, ..., l_{n-1}] tmp = f.readline() tmp = [int(b) for b in tmp.split()] Sm = list(tmp) f.close() except IOError: print("// Strategies to be computed") # List of Small Isogeny Degree, Lp := [l_0, ..., l_{n-1}] [We need to # include case l=2 and l=4] Sp, Cp = dynamic_programming_algorithm(SIDp[::-1], len(SIDp)) # List of Small Isogeny Degree, Lm := [l_0, ..., l_{n-1}] Sm, Cm = dynamic_programming_algorithm(SIDm[::-1], len(SIDm)) f = open(f_name, 'w') f.writelines(' '.join([str(tmp) for tmp in Sp]) + '\n') f.writelines(' '.join([str(tmp) for tmp in Sm]) + '\n') f.close() print( "// All the experiments are assuming S = %1.6f x M and a = %1.6f x M. The curve.measures are given in millions of field operations.\n" % (SQR, ADD)) print("p := 0x%X;" % p) print("fp := GF(p);") print("_<x> := PolynomialRing(fp);") print("fp2<i> := ext<fp | x^2 + 1>;") print("Pr<x> := PolynomialRing(fp2);") # Reading public generators points f = open(resource_filename('sidh', 'data/gen/' + setting.prime)) # x(PA), x(QA) and x(PA - QA) PQA = f.readline() PQA = [int(x, 16) for x in PQA.split()] PA = [list(PQA[0:2]), [0x1, 0x0]] QA = [list(PQA[2:4]), [0x1, 0x0]] PQA = [list(PQA[4:6]), [0x1, 0x0]] # x(PB), x(QB) and x(PB - QB) PQB = f.readline() PQB = [int(x, 16) for x in PQB.split()] PB = [list(PQB[0:2]), [0x1, 0x0]] QB = [list(PQB[2:4]), [0x1, 0x0]] PQB = [list(PQB[4:6]), [0x1, 0x0]] f.close() A = [[0x8, 0x0], [0x4, 0x0]] a = coeff(A) print("public_coeff := 0x%X + i * 0x%X;\n" % (a[0], a[1])) print( "// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------" ) print("// Public Key Generation") print( "// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n" ) # Alice's side print("// Private key corresponding to Alice") a_private = algo.gae.random_key(p + 1) fp.fp.set_zero_ops() Ra = curve.Ladder3pt(a_private, PA, QA, PQA, A) print("// sk_a := 0x%X;" % a_private) RUNNING_TIME = fp.fp.get_ops() print( "// kernel point generator cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;\n" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) print("// Public key corresponding to Alice") fp.fp.set_zero_ops() a_public, PB_a, QB_a, PQB_a = algo.gae.evaluate_strategy( True, PB, QB, PQB, A, Ra, SIDp[::-1], Sp, len(SIDp)) RUNNING_TIME = fp.fp.get_ops() print("// isogeny evaluation cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) a_curve = coeff(a_public) print("pk_a := 0x%X + i * 0x%X;\n" % (a_curve[0], a_curve[1])) # print("B := EllipticCurve(x^3 + (0x%X + i * 0x%X )* x^2 + x);" % (a_curve[0], a_curve[1]) ) # print("assert(Random(B) * (p + 1) eq B!0);") print("// Private key corresponding to Bob") b_private = algo.gae.random_key(p - 1) print("// sk_b := 0x%X;" % b_private) fp.fp.set_zero_ops() Rb = curve.Ladder3pt(b_private, PB, QB, PQB, A) RUNNING_TIME = fp.fp.get_ops() print( "// kernel point generator cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;\n" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) print("// Public key corresponding to Bob") fp.fp.set_zero_ops() b_public, PA_b, QA_b, PQA_b = algo.gae.evaluate_strategy( True, PA, QA, PQA, A, Rb, SIDm[::-1], Sm, len(SIDm)) RUNNING_TIME = fp.fp.get_ops() print("// isogeny evaluation cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) b_curve = coeff(b_public) print("pk_b := 0x%X + i * 0x%X;\n" % (b_curve[0], b_curve[1])) # print("B := EllipticCurve(x^3 + (0x%X + i * 0x%X )* x^2 + x);" % (b_curve[0], b_curve[1]) ) # print("assert(Random(B) * (p + 1) eq B!0);") # ====================================================== print( "\n// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------" ) print("// Secret Sharing Computation") print( "// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n" ) print("// Secret sharing corresponding to Alice") fp.fp.set_zero_ops() RB_a = curve.Ladder3pt(a_private, PA_b, QA_b, PQA_b, b_public) RUNNING_TIME = fp.fp.get_ops() print( "// kernel point generator cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) fp.fp.set_zero_ops() ss_a, _, _, _ = algo.gae.evaluate_strategy(False, PB, QB, PQB, b_public, RB_a, SIDp[::-1], Sp, len(SIDp)) RUNNING_TIME = fp.fp.get_ops() print("// isogeny evaluation cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) ss_a_curve = coeff(ss_a) print("ss_a := 0x%X + i * 0x%X;\n" % (ss_a_curve[0], ss_a_curve[1])) # ss_ja = jinvariant(ss_a) # print("B := EllipticCurve(x^3 + (0x%X + i * 0x%X )* x^2 + x);" % (ss_a_curve[0], ss_a_curve[1]) ) # print("jB := 0x%X + i * 0x%X;" % (ss_ja[0], ss_ja[1]) ) # print("assert(Random(B) * (p + 1) eq B!0);") # print("assert(jInvariant(B) eq jB);") print("// Secret sharing corresponding to Bob") fp.fp.set_zero_ops() RA_b = curve.Ladder3pt(b_private, PB_a, QB_a, PQB_a, a_public) RUNNING_TIME = fp.fp.get_ops() print( "// kernel point generator cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) fp.fp.set_zero_ops() ss_b, _, _, _ = algo.gae.evaluate_strategy(False, PA, QA, PQA, a_public, RA_b, SIDm[::-1], Sm, len(SIDm)) RUNNING_TIME = fp.fp.get_ops() print("// isogeny evaluation cost:\t%2.3fM + %2.3fS + %2.3fa = %2.3fM;" % ( RUNNING_TIME[0] / (10.0**6), RUNNING_TIME[1] / (10.0**6), RUNNING_TIME[2] / (10.0**6), curve.measure(RUNNING_TIME) / (10.0**6), )) ss_b_curve = coeff(ss_b) print("ss_b := 0x%X + i * 0x%X;\n" % (ss_b_curve[0], ss_b_curve[1])) # ss_jb = jinvariant(ss_b) # print("B := EllipticCurve(x^3 + (0x%X + i * 0x%X )* x^2 + x);" % (ss_b_curve[0], ss_b_curve[1]) ) # print("jB := 0x%X + i * 0x%X;" % (ss_jb[0], ss_jb[1]) ) # print("assert(Random(B) * (p + 1) eq B!0);") # print("assert(jInvariant(B) eq jB);") print( "\n// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------" ) if ss_a_curve == ss_b_curve: print('\x1b[0;30;43m' + '\"Successfully passed!\";' + '\x1b[0m') else: print('\x1b[0;30;41m' + '\"Great Scott!... The sky is falling. NOT PASSED!!!\"' + '\x1b[0m') return attrdict(name='bsidh-main', **locals())
def _prepare_eletronic_doc_vals(self): invoice = self num_controle = int(''.join( [str(SystemRandom().randrange(9)) for i in range(8)])) numero_nfe = numero_rps = 0 if self.company_id.l10n_br_nfe_sequence: numero_nfe = self.company_id.l10n_br_nfe_sequence.next_by_id() if self.company_id.l10n_br_nfe_service_sequence: numero_rps = self.company_id.l10n_br_nfe_service_sequence.next_by_id( ) vals = { 'name': invoice.name, 'move_id': invoice.id, 'company_id': invoice.company_id.id, 'schedule_user_id': self.env.user.id, 'state': 'draft', 'tipo_operacao': TYPE2EDOC[invoice.type], 'numero_controle': num_controle, 'data_emissao': datetime.now(), 'data_agendada': invoice.invoice_date, 'finalidade_emissao': '1', 'ambiente': invoice.company_id.l10n_br_tipo_ambiente, 'partner_id': invoice.partner_id.id, 'payment_term_id': invoice.invoice_payment_term_id.id, 'fiscal_position_id': invoice.fiscal_position_id.id, 'natureza_operacao': invoice.fiscal_position_id.name, 'ind_pres': invoice.fiscal_position_id.ind_pres, 'finalidade_emissao': invoice.fiscal_position_id.finalidade_emissao, # 'valor_icms': invoice.icms_value, # 'valor_icmsst': invoice.icms_st_value, # 'valor_ipi': invoice.ipi_value, # 'valor_pis': invoice.pis_value, # 'valor_cofins': invoice.cofins_value, # 'valor_ii': invoice.ii_value, 'valor_bruto': invoice.amount_total, # 'valor_desconto': invoice.total_desconto, 'valor_final': invoice.amount_total, # 'valor_bc_icms': invoice.icms_base, # 'valor_bc_icmsst': invoice.icms_st_base, # 'valor_estimado_tributos': invoice.total_tributos_estimados, # 'valor_retencao_pis': invoice.pis_retention, # 'valor_retencao_cofins': invoice.cofins_retention, # 'valor_bc_irrf': invoice.irrf_base, # 'valor_retencao_irrf': invoice.irrf_retention, # 'valor_bc_csll': invoice.csll_base, # 'valor_retencao_csll': invoice.csll_retention, # 'valor_bc_inss': invoice.inss_base, # 'valor_retencao_inss': invoice.inss_retention, 'informacoes_complementares': invoice.narration, 'numero_fatura': invoice.name, 'fatura_bruto': invoice.amount_total, 'fatura_desconto': 0.0, 'fatura_liquido': invoice.amount_total, 'pedido_compra': invoice.invoice_payment_ref, 'serie_documento': invoice.fiscal_position_id.serie_nota_fiscal, 'numero': numero_nfe, 'numero_rps': numero_rps, } vals[ 'cod_regime_tributario'] = '1' if invoice.company_id.l10n_br_tax_regime == 'simples' else '3' # Indicador Consumidor Final if invoice.commercial_partner_id.is_company: vals['ind_final'] = '0' else: vals['ind_final'] = '1' vals['ind_dest'] = '1' if invoice.company_id.state_id != invoice.commercial_partner_id.state_id: vals['ind_dest'] = '2' if invoice.company_id.country_id != invoice.commercial_partner_id.country_id: vals['ind_dest'] = '3' if invoice.fiscal_position_id.ind_final: vals['ind_final'] = invoice.fiscal_position_id.ind_final # Indicador IE Destinatário ind_ie_dest = False if invoice.commercial_partner_id.is_company: if invoice.commercial_partner_id.l10n_br_inscr_est: ind_ie_dest = '1' elif invoice.commercial_partner_id.state_id.code in ('AM', 'BA', 'CE', 'GO', 'MG', 'MS', 'MT', 'PE', 'RN', 'SP'): ind_ie_dest = '9' elif invoice.commercial_partner_id.country_id.code != 'BR': ind_ie_dest = '9' else: ind_ie_dest = '2' else: ind_ie_dest = '9' if invoice.commercial_partner_id.l10n_br_indicador_ie_dest: ind_ie_dest = invoice.commercial_partner_id.l10n_br_indicador_ie_dest vals['ind_ie_dest'] = ind_ie_dest iest_id = invoice.company_id.l10n_br_iest_ids.filtered( lambda x: x.state_id == invoice.commercial_partner_id.state_id) if iest_id: vals['iest'] = iest_id.name total_produtos = total_servicos = 0.0 for inv_line in self.invoice_line_ids: if inv_line.product_id.type == 'service': total_servicos += inv_line.price_subtotal else: total_produtos += inv_line.price_subtotal vals.update({ 'valor_servicos': total_servicos, 'valor_produtos': total_produtos, }) return vals
def test_check_valid_path(self): # success case: input the valid path path = [ self.connector_token_list[0], self.flexible_token_address_list[0], self.connector_token_list[1] ] self.network_score._require_valid_path(path) # failure case: input path whose length under 3 invalid_path = [ self.connector_token_list[0], self.flexible_token_address_list[0] ] self.assertRaises(RevertException, self.network_score._require_valid_path, invalid_path) # failure case: input path whose length is more than 21 random = SystemRandom() # use random data to avoid same address is made invalid_path = [ Address.from_string("cx" + str(random.randrange(10)) + str(random.randrange(10)) * 39) in range(0, 22) ] self.assertRaises(RevertException, self.network_score._require_valid_path, invalid_path) # failure case: input path whose length is even invalid_path = [ self.connector_token_list[0], self.flexible_token_address_list[0], self.connector_token_list[1], self.flexible_token_address_list[1] ] self.assertRaises(RevertException, self.network_score._require_valid_path, invalid_path) # failure case: input path which has the same flexible token address in it invalid_path = [ self.connector_token_list[0], self.flexible_token_address_list[0], self.connector_token_list[1], self.flexible_token_address_list[0], self.connector_token_list[1] ] self.assertRaises(RevertException, self.network_score._require_valid_path, invalid_path) # success case: input path which has the same flexible token address in the 'from' or 'to' position in it # path: [connector0 - flexible token0 - flexible token1 - flexible token2, flexible token0] path = [ self.connector_token_list[0], self.flexible_token_address_list[0], self.flexible_token_address_list[1], self.flexible_token_address_list[2], self.flexible_token_address_list[0] ] self.network_score._require_valid_path(path) # success case: input path which has the same flexible tokens that only exist in 'from' or 'to' in it path = [ self.flexible_token_address_list[0], self.flexible_token_address_list[1], self.connector_token_list[0], self.flexible_token_address_list[2], self.flexible_token_address_list[0] ] self.network_score._require_valid_path(path)
def make_password(length): generator = SystemRandom() chars = string.ascii_letters + string.digits + '!@#$%^&*()' return ''.join(generator.choice(chars) for i in range(length))
def gen_access_key(self): rs = Rstr(SystemRandom()) self.access_key = rs.xeger(r'[A-Z]\d[A-Z]-\d[A-Z]\d') return self.access_key
def generate_secret_key(ctx): """Generate Django SECRET_KEY""" charset = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)" print(''.join([SystemRandom().choice(charset) for i in range(50)]))
def _prepare_edoc_vals(self, invoice, inv_lines, serie_id): num_controle = int(''.join([str(SystemRandom().randrange(9)) for i in range(8)])) vals = { 'name': invoice.number, 'invoice_id': invoice.id, 'code': invoice.number, 'company_id': invoice.company_id.id, 'schedule_user_id': self.env.user.id, 'state': 'draft', 'tipo_operacao': TYPE2EDOC[invoice.type], 'numero_controle': num_controle, 'data_emissao': datetime.now(), 'data_agendada': invoice.date_invoice, 'data_fatura': datetime.now(), 'finalidade_emissao': '1', 'partner_id': invoice.partner_id.id, 'payment_term_id': invoice.payment_term_id.id, 'fiscal_position_id': invoice.fiscal_position_id.id, 'valor_icms': invoice.icms_value, 'valor_icmsst': invoice.icms_st_value, 'valor_ipi': invoice.ipi_value, 'valor_pis': invoice.pis_value, 'valor_cofins': invoice.cofins_value, 'valor_ii': invoice.ii_value, 'valor_bruto': invoice.total_bruto, 'valor_desconto': invoice.total_desconto, 'valor_final': invoice.amount_total, 'valor_bc_icms': invoice.icms_base, 'valor_bc_icmsst': invoice.icms_st_base, 'valor_servicos': invoice.issqn_base, 'valor_bc_issqn': invoice.issqn_base, 'valor_issqn': invoice.issqn_value, 'valor_estimado_tributos': invoice.total_tributos_estimados, 'valor_retencao_issqn': invoice.issqn_retention, 'valor_retencao_pis': invoice.pis_retention, 'valor_retencao_cofins': invoice.cofins_retention, 'valor_bc_irrf': invoice.irrf_base, 'valor_retencao_irrf': invoice.irrf_retention, 'valor_bc_csll': invoice.csll_base, 'valor_retencao_csll': invoice.csll_retention, 'valor_bc_inss': invoice.inss_base, 'valor_retencao_inss': invoice.inss_retention, } total_produtos = total_servicos = 0.0 eletronic_items = [] for inv_line in inv_lines: if inv_line.product_type == 'service': total_servicos += inv_line.valor_bruto else: total_produtos += inv_line.valor_bruto eletronic_items.append((0, 0, self._prepare_edoc_item_vals(inv_line))) vals.update({ 'eletronic_item_ids': eletronic_items, 'valor_servicos': total_servicos, 'valor_bruto': total_produtos, }) return vals
from hashlib import md5 from random import SystemRandom pw = "kpdCE8aSt2gaqKKcU" r = SystemRandom() pwlen = len(pw) itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" salt = "".join(r.choice(itoa64) for i in range(8)) p = pw pp = pw+pw ps = pw+salt psp = pw+salt+pw sp = salt+pw spp = salt+pw+pw permutations = [ (p , psp), (spp, pp), (spp, psp), (pp, ps ), (spp, pp), (spp, psp), (pp, psp), (sp , pp), (spp, psp), (pp, psp), (spp, p ), (spp, psp), (pp, psp), (spp, pp), (sp , psp), (pp, psp), (spp, pp), (spp, ps ), (pp, psp), (spp, pp), (spp, psp) ] # Start digest "a" da = md5(pw + "$1$" + salt) # Create digest "b" db = md5(psp).digest() # Update digest "a" by repeating digest "b", providing "pwlen" bytes:
__all__ = ('Response', 'Twilio') from string import ascii_letters, digits from random import SystemRandom from functools import wraps from six.moves.urllib.parse import urlsplit, urlunsplit from twilio.rest import Client from twilio.request_validator import RequestValidator from twilio.twiml import TwiML from flask import Response as FlaskResponse from flask import abort, current_app, make_response, request, url_for from flask import _app_ctx_stack as stack from itsdangerous import TimestampSigner rand = SystemRandom() letters_and_digits = ascii_letters + digits class Response(FlaskResponse, TwiML): """ A response class for constructing TwiML documents, providing all of the verbs that are available through :py:class:`twilio.twiml.Response`. See also https://www.twilio.com/docs/api/twiml. """ def __init__(self, *args, **kwargs): TwiML.__init__(self) FlaskResponse.__init__(self, *args, **kwargs) @property
def random_ascii_string(length): random = SystemRandom() return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in xrange(length)])
def random_hash(): return hashlib.sha1(str(SystemRandom().random())).hexdigest()