Create nonce for server and salt, expiring after
$Auth_OpenID_SKEW seconds.
556872
function useNonce($server_url, $timestamp, $salt)
    {
        global $Auth_OpenID_SKEW;
        
        // save one request to memcache when nonce obviously expired 
        if (abs($timestamp - time()) > $Auth_OpenID_SKEW) {
            return false;
        }
        
        // SETNX will set the value only of the key doesn't exist yet.
        $nonceKey = $this->nonceKey($server_url, $salt);
        $added = $this->redis->setnx($nonceKey, "1");
        if ($added) {
            // Will set expiration
            $this->redis->expire($nonceKey, $Auth_OpenID_SKEW);
            return true;
        } else {
            return false;
        }
    }
792795
def _generateForTokenSecurity(self,
                                  username,
                                  password,
                                  referer=None,
                                  tokenUrl=None,
                                  expiration=None,
                                  proxy_url=None,
                                  proxy_port=None):
        
        if referer is None:
            referer = self._referer_url
        if tokenUrl is None:
            tokenUrl  = self._token_url

        query_dict = {'username': self._username,
                      'password': self._password,
                      'expiration': str(_defaultTokenExpiration),
                      'referer': referer,
                      'f': 'json'}
        if expiration is not None:
            query_dict['expiration'] = str(expiration)
        self._token_created_on = datetime.datetime.now()
        token = self._post(url=tokenUrl,
                              param_dict=query_dict,
                              securityHandler=None,
                              proxy_port=self._proxy_port,
                              proxy_url=self._proxy_url)
        if 'error' in token:
            self._token = None
            return token


        self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] / 1000) - \
            datetime.timedelta(seconds=10)
        if "token" not in token:
            self._token = None
            return None
        else:
            httpPrefix = self._url
            if token['ssl'] == True:
                httpPrefix = self._surl
            self._token = token['token']
            return token['token'], httpPrefix
985973
def prep_jid(nocache=False, passed_jid=None):
    '''
    
    '''
    if passed_jid is None:
        jid = salt.utils.jid.gen_jid(__opts__)
    else:
        jid = passed_jid

    cb_ = _get_connection()

    try:
        cb_.add(six.text_type(jid),
               {'nocache': nocache},
               ttl=_get_ttl(),
               )
    except couchbase.exceptions.KeyExistsError:
        # TODO: some sort of sleep or something? Spinning is generally bad practice
        if passed_jid is None:
            return prep_jid(nocache=nocache)

    return jid
1031971
private function cspGenerateNonce()
    {
        $nonce = base64_encode(
            openssl_random_pseudo_bytes(30, $isCryptoStrong)
        );

        if ( ! $isCryptoStrong)
        {
            $this->addError(
                'OpenSSL (openssl_random_pseudo_bytes) reported that it did
                <strong>not</strong> use a cryptographically strong algorithm
                to generate the nonce for CSP.',

                E_USER_WARNING
            );
        }

        return $nonce;
    }
270145
def sign_jwt(data, secret_key, expires_in, salt=None, **kw):
    
    s = itsdangerous.TimedJSONWebSignatureSerializer(secret_key=secret_key,
                                                     expires_in=expires_in,
                                                     salt=salt,
                                                      **kw)
    return s.dumps(data)
310198
def generate_nonce_timestamp():
    
    global count
    rng = botan.rng().get(30)
    uuid4 = uuid.uuid4().bytes  # 16 byte
    tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng
    nonce = tmpnonce[:41]  # 41 byte (328 bit)
    count += 1
    return nonce
1055738
def _authenticate_mongo_cr(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    # Get a nonce
    response = sock_info.command(source, {'getnonce': 1})
    nonce = response['nonce']
    key = _auth_key(nonce, username, password)

    # Actually authenticate
    query = SON([('authenticate', 1),
                 ('user', username),
                 ('nonce', nonce),
                 ('key', key)])
    sock_info.command(source, query)
1254864
def _preflight_check(desired, fromrepo, **kwargs):
    '''
    
    '''
    if 'pkg.check_db' not in __salt__:
        return {}
    ret = {'suggest': {}, 'no_suggest': []}
    pkginfo = __salt__['pkg.check_db'](
        *list(desired.keys()), fromrepo=fromrepo, **kwargs
    )
    for pkgname in pkginfo:
        if pkginfo[pkgname]['found'] is False:
            if pkginfo[pkgname]['suggestions']:
                ret['suggest'][pkgname] = pkginfo[pkgname]['suggestions']
            else:
                ret['no_suggest'].append(pkgname)
    return ret
697340
def create_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ):
    
    
    from .bitcoin_blockchain import AuthServiceProxy

    global do_wrap_socket, create_ssl_authproxy
        
    log.debug("[%s] Connect to bitcoind at %s://%s@%s:%s, timeout=%s" % (os.getpid(), 'https' if use_https else 'http', rpc_username, server, port, timeout) )
    
    protocol = 'https' if use_https else 'http'
    if not server or len(server) < 1:
        raise Exception('Invalid bitcoind host address.')
    if not port or not is_valid_int(port):
        raise Exception('Invalid bitcoind port number.')
    
    authproxy_config_uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port)
    
    if use_https:
        # TODO: ship with a cert
        if do_wrap_socket:
           # ssl._create_unverified_context and ssl.create_default_context are not supported.
           # wrap the socket directly 
           connection = BitcoindConnection( server, int(port), timeout=timeout )
           ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
           
        elif create_ssl_authproxy:
           # ssl has _create_unverified_context, so we're good to go 
           ret = AuthServiceProxy(authproxy_config_uri, timeout=timeout)
        
        else:
           # have to set up an unverified context ourselves 
           ssl_ctx = ssl.create_default_context()
           ssl_ctx.check_hostname = False
           ssl_ctx.verify_mode = ssl.CERT_NONE
           connection = httplib.HTTPSConnection( server, int(port), context=ssl_ctx, timeout=timeout )
           ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
          
    else:
        ret = AuthServiceProxy(authproxy_config_uri)

    # remember the options 
    bitcoind_opts = {
       "bitcoind_user": rpc_username,
       "bitcoind_passwd": rpc_password,
       "bitcoind_server": server,
       "bitcoind_port": port,
       "bitcoind_use_https": use_https,
       "bitcoind_timeout": timeout
    }
    
    setattr( ret, "opts", bitcoind_opts )
    return ret
702577
def expire(key, seconds, host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.expire(key, seconds)
1219739
def create(name, allocated_storage, db_instance_class, engine,
           master_username, master_user_password, db_name=None,
           db_security_groups=None, vpc_security_group_ids=None,
           vpc_security_groups=None, availability_zone=None,
           db_subnet_group_name=None, preferred_maintenance_window=None,
           db_parameter_group_name=None, backup_retention_period=None,
           preferred_backup_window=None, port=None, multi_az=None,
           engine_version=None, auto_minor_version_upgrade=None,
           license_model=None, iops=None, option_group_name=None,
           character_set_name=None, publicly_accessible=None, wait_status=None,
           tags=None, db_cluster_identifier=None, storage_type=None,
           tde_credential_arn=None, tde_credential_password=None,
           storage_encrypted=None, kms_key_id=None, domain=None,
           copy_tags_to_snapshot=None, monitoring_interval=None,
           monitoring_role_arn=None, domain_iam_role_name=None, region=None,
           promotion_tier=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    if not allocated_storage:
        raise SaltInvocationError('allocated_storage is required')
    if not db_instance_class:
        raise SaltInvocationError('db_instance_class is required')
    if not engine:
        raise SaltInvocationError('engine is required')
    if not master_username:
        raise SaltInvocationError('master_username is required')
    if not master_user_password:
        raise SaltInvocationError('master_user_password is required')
    if availability_zone and multi_az:
        raise SaltInvocationError('availability_zone and multi_az are mutually'
                                  ' exclusive arguments.')
    if wait_status:
        wait_stati = ['available', 'modifying', 'backing-up']
        if wait_status not in wait_stati:
            raise SaltInvocationError(
                'wait_status can be one of: {0}'.format(wait_stati))
    if vpc_security_groups:
        v_tmp = __salt__['boto_secgroup.convert_to_group_ids'](
                groups=vpc_security_groups, region=region, key=key, keyid=keyid,
                profile=profile)
        vpc_security_group_ids = (vpc_security_group_ids + v_tmp
                                  if vpc_security_group_ids else v_tmp)

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {'results': bool(conn)}

        kwargs = {}
        boto_params = set(boto3_param_map.keys())
        keys = set(locals().keys())
        tags = _tag_doc(tags)

        for param_key in keys.intersection(boto_params):
            val = locals()[param_key]
            if val is not None:
                mapped = boto3_param_map[param_key]
                kwargs[mapped[0]] = mapped[1](val)

        # Validation doesn't want parameters that are None
        # https://github.com/boto/boto3/issues/400
        kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v is not None)

        rds = conn.create_db_instance(**kwargs)

        if not rds:
            return {'created': False}
        if not wait_status:
            return {'created': True, 'message':
                    'RDS instance {0} created.'.format(name)}

        while True:
            jmespath = 'DBInstances[*].DBInstanceStatus'
            status = describe_db_instances(name=name, jmespath=jmespath,
                                           region=region, key=key, keyid=keyid,
                                           profile=profile)
            if status:
                stat = status[0]
            else:
                # Whoops, something is horribly wrong...
                return {'created': False,
                        'error': "RDS instance {0} should have been created but"
                                 " now I can't find it.".format(name)}
            if stat == wait_status:
                return {'created': True,
                        'message': 'RDS instance {0} created (current status '
                        '{1})'.format(name, stat)}
            time.sleep(10)
            log.info('Instance status after 10 seconds is: %s', stat)

    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
64275
function createUser(name, pass, cb) {
  // Check name
  if(!isValidName(name)) return cb(new Error('Invalid name "'+name+'"'))
  // Check pass
  if(!isValidPass(pass)) return cb(new Error('Invalid pass: "'+pass+'"'))
  // gen salt
  var salt = crypto.randomBytes(16).toString('hex')
  // gen sha1
  var hash = crypto.createHash('sha1')
  hash.update(pass)
  hash.update(salt)
  var password_sha = hash.digest('hex')
  
  var new_doc =
      { _id: user_namespace+':'+name
      , name: name
      , roles: []
      , type: 'user'
      , password_sha: password_sha
      , salt: salt
      }
    ;
  
  nano().use(user_dbname).insert(new_doc, function(err, doc, h) {
    if(err) return cb(err)
    
    // Every user gets its own database
    createDatabase(name, function(err) {
      if(err) return cb(err)
      
      // Sets the _security
      setDatabaseSecurity(name, function(err) {
        if(err) return cb(err)
        cb(null, doc.id, doc.rev)
      })
    })
  })
}
1332475
def clean_expired_tokens(opts):
    '''
    
    '''
    loadauth = salt.auth.LoadAuth(opts)
    for tok in loadauth.list_tokens():
        token_data = loadauth.get_tok(tok)
        if 'expire' not in token_data or token_data.get('expire', 0) < time.time():
            loadauth.rm_token(tok)
985006
def _makeCertificate(key, email, _utcnow=datetime.utcnow):
    
    # Create a certificate for this key.
    cert = X509()
    cert.set_pubkey(key)

    # Set the subject.
    subject = cert.get_subject()
    subject.CN = u"Crypto 101 Client"
    subject.emailAddress = email

    # Expiration dates. Mandatory.
    now = _utcnow()
    start = now.replace(hour=0, minute=0, second=0)
    cert.set_notBefore(start.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
    end = start.replace(year=start.year + 5)
    cert.set_notAfter(end.strftime(_ASN1_GENERALIZEDTIME_FORMAT))

    # Self-sign.
    cert.set_issuer(cert.get_subject())
    cert.sign(key, "sha512")

    return cert
453125
function createAccount (commandOptions, { accountName, domainId, publicKey }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'createAccount',
      {
        accountName,
        domainId,
        publicKey
      }
    )
  )
}
1002289
def create(self, secret, **kwargs):
        
        parameters = {"adminClientSecret": secret}
        self.service.create(parameters=parameters)

        # Store URI into environment variable
        predix.config.set_env_value(self.use_class, 'uri', self._get_uri())

        # Once we create it login
        self.authenticate()
1098031
public function auth($nonce = null, $params = null)
    {
        $params = $params ?: array();

        $client_id = $this->params['client_id'];
        $client_key = $this->params['client_key'];

        // 1) Get nonce
        $nonce = $nonce ?: $this->server->request('auth');

        // 2) Create key hash
        $key_hash = md5("{$client_id}::{$client_key}");

        // 3) Create auth key
        $auth_key = md5("{$nonce}{$client_id}{$key_hash}");

        // 4) Authenticate with client params
        $params['client'] = $client_id;
        $params['key'] = $auth_key;

        if ($this->params['version']) {
            $params['$v'] = $this->params['version'];
        }
        if ($this->params['api']) {
            $params['$api'] = $this->params['api'];
        }
        if ($this->params['session']) {
            $params['$session'] = $this->params['session'];
        }
        if (isset($this->params['route']['client'])) {
            $params['$route'] = $this->params['route'];
        }
        if (isset($_SERVER['REMOTE_ADDR']) && $ip_address = $_SERVER['REMOTE_ADDR']) {
            $params['$ip'] = $ip_address;
        }
        if ($this->cache) {
            $params['$cached'] = $this->cache->get_versions();
        }

        $this->authed = true;
        
        try {
            return $this->server->request('auth', $params);
        } catch (NetworkException $e) {
            $this->request_rescue($e);
            return $this->auth();
        }
    }