generate a pseudo salt (used, if user is wrong)
439564
def get_pseudo_salt(length, *args):
    
    temp = "".join([arg for arg in args])
    return hash_hexdigest(temp)[:length]
681808
def getent(refresh=False):
    '''
    
    '''
    if 'user.getent' in __context__ and not refresh:
        return __context__['user.getent']

    ret = []
    for data in pwd.getpwall():
        ret.append(_format_info(data))
    __context__['user.getent'] = ret
    return ret
4687
function cmd_encrypt_password(args, done) {
    // 128 bits of salt
    var salt = args.salt || create_salt()
    var password = args.password

    hasher(pepper + password + salt, options.rounds, function(pass) {
      done(null, { ok: true, pass: pass, salt: salt })
    })
  }
294038
def kdf_salt(self):
        

        encryption_algo = self['algorithm'].native

        if encryption_algo == 'pbes2':
            salt = self['parameters']['key_derivation_func']['parameters']['salt']

            if salt.name == 'other_source':
                raise ValueError(unwrap(
                    '''
                    Can not determine key derivation salt - the
                    reserved-for-future-use other source salt choice was
                    specified in the PBKDF2 params structure
                    '''
                ))

            return salt.native

        if encryption_algo.find('.') == -1:
            if encryption_algo.find('_') != -1:
                return self['parameters']['salt'].native

            raise ValueError(unwrap(
                '''
                Encryption algorithm "%s" does not have a registered key
                derivation function
                ''',
                encryption_algo
            ))

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s", can not determine key
            derivation salt
            ''',
            encryption_algo
        ))
507459
function (password, algorithm, salt) {
            salt = salt || Crypto.randomBytes(128).toString("hex");
            algorithm = algorithm || this.$.algorithm;

            var hash = Crypto.createHash(this.$.algorithm);
            hash.update(salt + password, "utf8");

            return [algorithm, salt, hash.digest("hex")].join(this.$.delimiter);
        }
586935
def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):
    '''
    
    '''
    if not HAS_CRYPT:
        raise SaltInvocationError('No crypt module for windows')

    hash_algorithms = dict(
        md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'
    )
    if algorithm not in hash_algorithms:
        raise SaltInvocationError(
            'Algorithm \'{0}\' is not supported'.format(algorithm)
        )

    if password is None:
        password = secure_password()

    if crypt_salt is None:
        crypt_salt = secure_password(8)

    crypt_salt = hash_algorithms[algorithm] + crypt_salt

    return crypt.crypt(password, crypt_salt)
909537
def _handle_salt_host_resource(resource):
    '''
    
    '''
    ret = {}
    attrs = resource.get('primary', {}).get('attributes', {})
    ret[MINION_ID] = attrs.get(MINION_ID)
    valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
    for attr in valid_attrs:
        ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
    return ret
1164844
def salt_main():
    '''
    
    '''
    import salt.cli.salt
    if '' in sys.path:
        sys.path.remove('')
    client = salt.cli.salt.SaltCMD()
    _install_signal_handlers(client)
    client.run()
1088125
def flush(name, family='ipv4', **kwargs):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    set_check = __salt__['ipset.check_set'](name)
    if set_check is False:
        ret['result'] = False
        ret['comment'] = ('ipset set {0} does not exist for {1}'
                          .format(name, family))
        return ret

    if __opts__['test']:
        ret['comment'] = 'ipset entries in set {0} for {1} would be flushed'.format(
            name,
            family)
        return ret
    if __salt__['ipset.flush'](name, family):
        ret['changes'] = {'locale': name}
        ret['result'] = True
        ret['comment'] = 'Flushed ipset entries from set {0} for {1}'.format(
            name,
            family
        )
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to flush ipset entries from set {0} for {1}' \
                         ''.format(name, family)
        return ret
1133216
def gen_salt
      chars = []
      8.times { chars << SALT_CHARS[SecureRandom.random_number(SALT_CHARS.size)] }
      chars.join('')
    end
816340
def _check_user(user, group):
    '''
    
    '''
    err = ''
    if user:
        uid = __salt__['file.user_to_uid'](user)
        if uid == '':
            err += 'User {0} is not available '.format(user)
    if group:
        gid = __salt__['file.group_to_gid'](group)
        if gid == '':
            err += 'Group {0} is not available'.format(group)
    return err
360678
def get_salt(request):
    
    try:
        username = request.POST["username"]
    except KeyError:
        # log.error("No 'username' in POST data?!?")
        return HttpResponseBadRequest()

    try:
        request.server_challenge = request.session[SERVER_CHALLENGE_KEY]
    except KeyError as err:
        # log.error("Can't get challenge from session: %s", err)
        return HttpResponseBadRequest()
    # log.debug("old challenge: %r", request.server_challenge)

    send_pseudo_salt=True

    form = UsernameForm(request, data=request.POST)
    if form.is_valid():
        send_pseudo_salt=False

        user_profile = form.user_profile
        init_pbkdf2_salt = user_profile.init_pbkdf2_salt
        if not init_pbkdf2_salt:
            # log.error("No init_pbkdf2_salt set in user profile!")
            send_pseudo_salt=True

        if len(init_pbkdf2_salt)!=app_settings.PBKDF2_SALT_LENGTH:
            # log.error("Salt for user %r has wrong length: %r" % (request.POST["username"], init_pbkdf2_salt))
            send_pseudo_salt=True
    # else:
        # log.error("Salt Form is not valid: %r", form.errors)

    if send_pseudo_salt:
        # log.debug("\nUse pseudo salt!!!")
        init_pbkdf2_salt = crypt.get_pseudo_salt(app_settings.PBKDF2_SALT_LENGTH, username)

    response = HttpResponse(init_pbkdf2_salt, content_type="text/plain")

    if not send_pseudo_salt:
        response.add_duration=True # collect duration time in @TimingAttackPreventer

    # log.debug("\nsend init_pbkdf2_salt %r to client.", init_pbkdf2_salt)
    return response
848343
def _run_runner(self):
        '''
        
        '''
        import salt.minion
        ret = {}
        low = {'fun': self.opts['fun']}
        try:
            # Allocate a jid
            async_pub = self._gen_async_pub()
            self.jid = async_pub['jid']

            fun_args = salt.utils.args.parse_input(
                    self.opts['arg'],
                    no_parse=self.opts.get('no_parse', []))

            verify_fun(self.functions, low['fun'])
            args, kwargs = salt.minion.load_args_and_kwargs(
                self.functions[low['fun']],
                fun_args)
            low['arg'] = args
            low['kwarg'] = kwargs

            if self.opts.get('eauth'):
                if 'token' in self.opts:
                    try:
                        with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_:
                            low['key'] = salt.utils.stringutils.to_unicode(fp_.readline())
                    except IOError:
                        low['token'] = self.opts['token']

                # If using eauth and a token hasn't already been loaded into
                # low, prompt the user to enter auth credentials
                if 'token' not in low and 'key' not in low and self.opts['eauth']:
                    # This is expensive. Don't do it unless we need to.
                    import salt.auth
                    resolver = salt.auth.Resolver(self.opts)
                    res = resolver.cli(self.opts['eauth'])
                    if self.opts['mktoken'] and res:
                        tok = resolver.token_cli(
                                self.opts['eauth'],
                                res
                                )
                        if tok:
                            low['token'] = tok.get('token', '')
                    if not res:
                        log.error('Authentication failed')
                        return ret
                    low.update(res)
                    low['eauth'] = self.opts['eauth']
            else:
                user = salt.utils.user.get_specific_user()

            if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']:
                low['kwarg']['orchestration_jid'] = async_pub['jid']

            # Run the runner!
            if self.opts.get('async', False):
                if self.opts.get('eauth'):
                    async_pub = self.cmd_async(low)
                else:
                    async_pub = self.asynchronous(self.opts['fun'],
                                                  low,
                                                  user=user,
                                                  pub=async_pub)

                # by default: info will be not enough to be printed out !
                log.warning(
                    'Running in asynchronous mode. Results of this execution may '
                    'be collected by attaching to the master event bus or '
                    'by examing the master job cache, if configured. '
                    'This execution is running under tag %s', async_pub['tag']
                )
                return async_pub['jid']  # return the jid

            # otherwise run it in the main process
            if self.opts.get('eauth'):
                ret = self.cmd_sync(low)
                if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}:
                    outputter = ret['outputter']
                    ret = ret['data']
                else:
                    outputter = None
                display_output(ret, outputter, self.opts)
            else:
                ret = self._proc_function(self.opts['fun'],
                                          low,
                                          user,
                                          async_pub['tag'],
                                          async_pub['jid'],
                                          daemonize=False)
        except salt.exceptions.SaltException as exc:
            evt = salt.utils.event.get_event('master', opts=self.opts)
            evt.fire_event({'success': False,
                            'return': '{0}'.format(exc),
                            'retcode': 254,
                            'fun': self.opts['fun'],
                            'fun_args': fun_args,
                            'jid': self.jid},
                           tag='salt/run/{0}/ret'.format(self.jid))
            # Attempt to grab documentation
            if 'fun' in low:
                ret = self.get_docs('{0}*'.format(low['fun']))
            else:
                ret = None

            # If we didn't get docs returned then
            # return the `not availble` message.
            if not ret:
                ret = '{0}'.format(exc)
            if not self.opts.get('quiet', False):
                display_output(ret, 'nested', self.opts)
        else:
            # If we don't have any values in ret by now, that's a problem.
            # Otherwise, we shouldn't be overwriting the retcode.
            if not ret:
                ret = {
                    'retcode': salt.defaults.exitcodes.EX_SOFTWARE,
                }
        log.debug('Runner return: %s', ret)

        return ret
1154617
function evpBytesToKey(password, salt, dkLen) {
  var digests = [md5(password + salt)];
  for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
    digests.push(md5(digests[i - 1] + password + salt));
  }
  return digests.join('').substr(0, dkLen);
}
618915
def salt_key():
    '''
    
    '''
    import salt.cli.key
    try:
        client = salt.cli.key.SaltKey()
        _install_signal_handlers(client)
        client.run()
    except Exception as err:
        sys.stderr.write("Error: {0}\n".format(err))
423205
def salt_cp():
    '''
    
    '''
    import salt.cli.cp
    client = salt.cli.cp.SaltCPCli()
    _install_signal_handlers(client)
    client.run()
1324919
def _prep_pub(self,
                  tgt,
                  fun,
                  arg,
                  tgt_type,
                  ret,
                  jid,
                  timeout,
                  **kwargs):
        '''
        
        '''
        if tgt_type == 'nodegroup':
            if tgt not in self.opts['nodegroups']:
                conf_file = self.opts.get(
                    'conf_file', 'the master config file'
                )
                raise SaltInvocationError(
                    'Node group {0} unavailable in {1}'.format(
                        tgt, conf_file
                    )
                )
            tgt = salt.utils.minions.nodegroup_comp(tgt,
                                                    self.opts['nodegroups'])
            tgt_type = 'compound'

        # Convert a range expression to a list of nodes and change expression
        # form to list
        if tgt_type == 'range' and HAS_RANGE:
            tgt = self._convert_range_to_list(tgt)
            tgt_type = 'list'

        # If an external job cache is specified add it to the ret list
        if self.opts.get('ext_job_cache'):
            if ret:
                ret += ',{0}'.format(self.opts['ext_job_cache'])
            else:
                ret = self.opts['ext_job_cache']

        # format the payload - make a function that does this in the payload
        #   module

        # Generate the standard keyword args to feed to format_payload
        payload_kwargs = {'cmd': 'publish',
                          'tgt': tgt,
                          'fun': fun,
                          'arg': arg,
                          'key': self.key,
                          'tgt_type': tgt_type,
                          'ret': ret,
                          'jid': jid}

        # if kwargs are passed, pack them.
        if kwargs:
            payload_kwargs['kwargs'] = kwargs

        # If we have a salt user, add it to the payload
        if self.opts['syndic_master'] and 'user' in kwargs:
            payload_kwargs['user'] = kwargs['user']
        elif self.salt_user:
            payload_kwargs['user'] = self.salt_user

        # If we're a syndication master, pass the timeout
        if self.opts['order_masters']:
            payload_kwargs['to'] = timeout

        return payload_kwargs