Returns a third-party caveat that, when added to a macaroon with
    add_caveat, results in a caveat with the location "local", encrypted with
    the given PublicKey.
    This can be automatically discharged by discharge_all passing a local key.
519304
def local_third_party_caveat(key, version):
    ''' 
    '''
    if version >= VERSION_2:
        loc = 'local {} {}'.format(version, key)
    else:
        loc = 'local {}'.format(key)
    return checkers.Caveat(location=loc, condition='')
558361
def check_first_party_caveat(self, ctx, cav):
        ''' 
        '''
        try:
            cond, arg = parse_caveat(cav)
        except ValueError as ex:
            # If we can't parse it, perhaps it's in some other format,
            # return a not-recognised error.
            return 'cannot parse caveat "{}": {}'.format(cav, ex.args[0])
        checker = self._checkers.get(cond)
        if checker is None:
            return 'caveat "{}" not satisfied: caveat not recognized'.format(
                cav)
        err = checker.check(ctx, cond, arg)
        if err is not None:
            return 'caveat "{}" not satisfied: {}'.format(cav, err)
640144
def _caveat_v2_to_dict(c):
    ''' 
    '''
    serialized = {}
    if len(c.caveat_id_bytes) > 0:
        _add_json_binary_field(c.caveat_id_bytes, serialized, 'i')
    if c.verification_key_id:
        _add_json_binary_field(c.verification_key_id, serialized, 'v')
    if c.location:
        serialized['l'] = c.location
    return serialized
62723
def crypto_config_from_kwargs(fallback, **kwargs):
    
    try:
        crypto_config = kwargs.pop("crypto_config")
    except KeyError:
        try:
            fallback_kwargs = {"table_name": kwargs["TableName"]}
        except KeyError:
            fallback_kwargs = {}
        crypto_config = fallback(**fallback_kwargs)
    return crypto_config, kwargs
1167943
def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"):
        """"""
        action_word = "moving" if del_after_upload else "copying"

        try:
            self.k.key = target_file  # setting the path (key) of file in the container

            if source == "filename":
                # grabs the contents from local_file address. Note that it loads the whole file into memory
                self.k.set_contents_from_filename(local_file, self.AWS_HEADERS)
            elif source == "fileobj":
                self.k.set_contents_from_file(local_file, self.AWS_HEADERS)
            elif source == "string":
                self.k.set_contents_from_string(local_file, self.AWS_HEADERS)
            else:
                raise Exception("%s is not implemented as a source." % source)
            self.k.set_acl(acl)  # setting the file permissions
            self.k.close()  # not sure if it is needed. Somewhere I read it is recommended.

            self.printv("%s %s to %s" % (action_word, local_file, target_file))
            # if it is supposed to delete the local file after uploading
            if del_after_upload and source == "filename":
                try:
                    os.remove(local_file)
                except:
                    logger.error("Unable to delete the file: ", local_file, exc_info=True)

            return True

        except:
            logger.error("Error in writing to %s", target_file, exc_info=True)
            return False
830441
function find3rdPartyCaveatParts(macaroonWithCaveat, secretPem) {
  var macaroonSerialized = macaroonWithCaveat.macaroon;
  var discharge = macaroonWithCaveat.discharge;

  var key = new NodeRSA();
  key.importKey(secretPem);

  var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);

  var getDischargeParts = getMacPartsFn(" = ");

  var macObj = macaroonPairsToObj(key.decrypt(discharge).toString('utf8'), getDischargeParts);

  var caveatKey = macObj.caveat_key;
  var message = macObj.message;

  var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);

  var getMacaroonParts = getMacPartsFn(" ");
  var stringMacPairs = macStringToPairs(macaroon.inspect(), getMacaroonParts);

  var identifierLoc = _.findIndex(stringMacPairs, function (pair) {
    return pair[0] === "cid" && pair[1] === "enc = " + discharge;
  });

  var caveatIdentifier = stringMacPairs[identifierLoc][1];
  var caveatLocation = stringMacPairs[identifierLoc + 2][1];//kind of a hack

  return {
    caveatKey: caveatKey,
    macRaw: macaroonSerialized,
    thirdParty: {
      messageObj: macaroonPairsToObj(macObj.message, getDischargeParts),
      identifier: caveatIdentifier,
      location: caveatLocation
    }
  };
}
1030200
function getRNG(){
	var randomBits, crypto;
	
	function construct(bits, arr, radix, size){
		var str = '',
			i = 0,
			len = arr.length-1;
		while( i<len || (str.length < bits) ){
			str += padLeft(parseInt(arr[i], radix).toString(2), size);
			i++;
		}
		str = str.substr(-bits);
		if( (str.match(/0/g)||[]).length === str.length){ // all zeros?
			return null;
		}else{
			return str;
		}
	}
	
	// node.js crypto.randomBytes()
	if(typeof require === 'function' && (crypto=require('crypto')) && (randomBits=crypto['randomBytes'])){
		return function(bits){
			var bytes = Math.ceil(bits/8),
				str = null;
		
			while( str === null ){
				str = construct(bits, randomBits(bytes).toString('hex'), 16, 4);
			}
			return str;
		}
	}
	
	// browsers with window.crypto.getRandomValues()
	if(global['crypto'] && typeof global['crypto']['getRandomValues'] === 'function' && typeof global['Uint32Array'] === 'function'){
		crypto = global['crypto'];
		return function(bits){
			var elems = Math.ceil(bits/32),
				str = null,
				arr = new global['Uint32Array'](elems);

			while( str === null ){
				crypto['getRandomValues'](arr);
				str = construct(bits, arr, 10, 32);
			}
			
			return str;	
		}
	}

	// A totally insecure RNG!!! (except in Safari)
	// Will produce a warning every time it is called.
	config.unsafePRNG = true;
	warn();
	
	var bitsPerNum = 32;
	var max = Math.pow(2,bitsPerNum)-1;
	return function(bits){
		var elems = Math.ceil(bits/bitsPerNum);
		var arr = [], str=null;
		while(str===null){
			for(var i=0; i<elems; i++){
				arr[i] = Math.floor(Math.random() * max + 1); 
			}
			str = construct(bits, arr, 10, bitsPerNum);
		}
		return str;
	};
}
10134
public void setAdditionalPublicanCfg(final String name, final String publicanCfg) {
        if (publicanCfg == null && !publicanCfgs.containsKey(name)) {
            return;
        } else if (publicanCfg == null) {
            removeChild(publicanCfgs.get(name));
            publicanCfgs.remove(name);
        } else if (!publicanCfgs.containsKey(name)) {
            final String fixedName = name + "-" + CommonConstants.CS_PUBLICAN_CFG_TITLE;
            final KeyValueNode<String> publicanCfgMetaData = new KeyValueNode<String>(fixedName, publicanCfg);
            publicanCfgs.put(name, publicanCfgMetaData);
            appendChild(publicanCfgMetaData, false);
        } else {
            publicanCfgs.get(name).setValue(publicanCfg);
        }
    }
275435
def is_local(self):
        
        return (isinstance(self.scope, CodeStatement)
                or (isinstance(self.scope, CodeFunction)
                    and self not in self.scope.parameters))
86741
function LocalStore(prefix) {
  prefix = prefix || 'openpgp-';
  this.publicKeysItem = prefix + this.publicKeysItem;
  this.privateKeysItem = prefix + this.privateKeysItem;
  if (typeof window !== 'undefined' && window.localStorage) {
    this.storage = window.localStorage;
  } else {
    this.storage = new (require('node-localstorage').LocalStorage)(config.node_store);
  }
}
1183475
public static void downloadResourcesAsSupervisorDirect(String key, String localFile,
                                                           ClientBlobStore cb) throws KeyNotFoundException, IOException {
        final int MAX_RETRY_ATTEMPTS = 2;
        final int ATTEMPTS_INTERVAL_TIME = 100;
        for (int retryAttempts = 0; retryAttempts < MAX_RETRY_ATTEMPTS; retryAttempts++) {
            if (downloadResourcesAsSupervisorAttempt(cb, key, localFile)) {
                break;
            }
            Utils.sleep(ATTEMPTS_INTERVAL_TIME);
        }
    }
395160
function checkIfLocalStorageThrows() {
    var localStorageTestKey = '_localforage_support_test';

    try {
        localStorage.setItem(localStorageTestKey, true);
        localStorage.removeItem(localStorageTestKey);

        return false;
    } catch (e) {
        return true;
    }
}
839488
def ensure_local_files():
	
	if _file_permissions:
		if not os.path.isdir(AUTH_DIR):
			os.mkdir(AUTH_DIR)
		for fn in [CONFIG_FILE]:
			contents = load_json_dict(fn)
			for key, val in list(_FILE_CONTENT[fn].items()):
				if key not in contents:
					contents[key] = val
			contents_keys = list(contents.keys())
			for key in contents_keys:
				if key not in _FILE_CONTENT[fn]:
					del contents[key]
			save_json_dict(fn, contents)
	else:
		warnings.warn("Looks like you don't have 'read-write' permission to "
					  "your 'home' ('~') directory")
831302
public LocalQPConsumerKey resolvedKey()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "resolvedKey");

    LocalQPConsumerKey key = null;

    if(generalMemberCount > 0)
    {
      // If we only have one this is easy
      if(singleMember != null)
        key = singleMember;
      // Otherwise, we try to be a little fair and pick the next one in
      // the list
      else
      {
        key = generalKeyMembers.get(generalMemberIndex);
        // Wrap the index if required
        if(++generalMemberIndex == generalMemberCount)
          generalMemberIndex = 0;
      }
    }
    else
    {
      // We should have at least one of these
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "resolvedKey", "SIErrorException");
        throw new SIErrorException(
          nls.getFormattedMessage(
            "INTERNAL_MESSAGING_ERROR_CWSIP0001",
            new Object[] {
              "com.ibm.ws.sib.processor.impl.LocalQPConsumerKeyGroup",
              "1:688:1.6.1.14" },
            null));
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "resolvedKey", key);

    return key;
  }
1286743
function mnemonicToPubKey(str) {

  var m = new Mnemonic(str);

  var xpriv1 = m.toHDPrivateKey(); // no passphrase

  var xpub1 = xpriv1.hdPublicKey;

  return xpub1
}
558475
def initialize_key_source
      detect_key_source
      if args.require_key? && !self.key
        log :error, 'Unable to determine the key, which appears to be required with current args'
        raise Sym::Errors::NoPrivateKeyFound, 'Private key is required when ' + (self.action ? self.action.to_s + 'ypting' : provided_flags.join(', '))
      end
      log :debug, "initialize_key_source: detected key ends with [...#{(key ? key[-5..-1] : 'nil').bold.magenta}]"
      log :debug, "opts: #{self.provided_value_options.to_s.green.bold}"
      log :debug, "flags: #{self.provided_flags.to_s.green.bold}"
    end
556075
async def authenticate_with_macaroon(url, insecure=False):
    """"""
    executor = futures.ThreadPoolExecutor(max_workers=1)

    def get_token():
        client = httpbakery.Client()
        resp = client.request(
            'POST', '{}/account/?op=create_authorisation_token'.format(url),
            verify=not insecure)
        if resp.status_code == HTTPStatus.UNAUTHORIZED:
            # if the auteentication with Candid fails, an exception is raised
            # above so we don't get here
            raise MacaroonLoginNotSupported(
                'Macaroon authentication not supported')
        if resp.status_code != HTTPStatus.OK:
            raise LoginError('Login failed: {}'.format(resp.text))
        result = resp.json()
        return '{consumer_key}:{token_key}:{token_secret}'.format(**result)

    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(executor, get_token)