Generate a secure password.
167073
def secure_password(length=20, use_random=True):
    '''
    
    '''
    try:
        length = int(length)
        pw = ''
        while len(pw) < length:
            if HAS_RANDOM and use_random:
                while True:
                    try:
                        char = salt.utils.stringutils.to_str(get_random_bytes(1))
                        break
                    except UnicodeDecodeError:
                        continue
                pw += re.sub(
                    salt.utils.stringutils.to_str(r'\W'),
                    str(),  # future lint: disable=blacklisted-function
                    char
                )
            else:
                pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
        return pw
    except Exception as exc:
        log.exception('Failed to generate secure passsword')
        raise CommandExecutionError(six.text_type(exc))
597418
def load_ldap_password(self):  # pragma: no cover
        """"""
        with open('{}/ldap.secret'.format(self.config_dir), 'r') as FILE:
            secure_config = FILE.read()
            self.user_pw = base64.b64decode(secure_config.encode())
301816
private function generatePassword($l = 8, $c = 0, $n = 0, $s = 0)
    {
        $count = $c + $n + $s;
        $out = '';
        if(!is_int($l) || !is_int($c) || !is_int($n) || !is_int($s)) {
            trigger_error('Argument(s) not an integer', E_USER_WARNING);
            return false;
        } else if($l < 0 || $l > 20 || $c < 0 || $n < 0 || $s < 0) {
            trigger_error('Argument(s) out of range', E_USER_WARNING);
            return false;
        } else if($c > $l) {
            trigger_error('Number of password capitals required exceeds password length', E_USER_WARNING);
            return false;
        } else if($n > $l) {
            trigger_error('Number of password numerals exceeds password length', E_USER_WARNING);
            return false;
        } else if($s > $l) {
            trigger_error('Number of password capitals exceeds password length', E_USER_WARNING);
            return false;
        } else if($count > $l) {
            trigger_error('Number of password special characters exceeds specified password length', E_USER_WARNING);
            return false;
        }
    
        $chars = "abcdefghijklmnopqrstuvwxyz";
        $caps = strtoupper($chars);
        $nums = "0123456789";
        $syms = "!@#$%^&*()-+?";
    
        for ($i = 0; $i < $l; $i++) {
            $out .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
    
        if($count) {
            $tmp1 = str_split($out);
            $tmp2 = array();
    
            for ($i = 0; $i < $c; $i++) {
                array_push($tmp2, substr($caps, mt_rand(0, strlen($caps) - 1), 1));
            } 
    
            for ($i = 0; $i < $n; $i++) {
                array_push($tmp2, substr($nums, mt_rand(0, strlen($nums) - 1), 1));
            }
    
            for ($i = 0; $i < $s; $i++) {
                array_push($tmp2, substr($syms, mt_rand(0, strlen($syms) - 1), 1));
            }
    
            $tmp1 = array_slice($tmp1, 0, $l - $count);
            $tmp1 = array_merge($tmp1, $tmp2);
            shuffle($tmp1);
            $out = implode('', $tmp1);
        }
    
        return $out;
    }
323351
public static String generatePassword(int length)
  {
    Params.strictPositive(length, "Password length");
    StringBuilder password = new StringBuilder(length);
    Random random = new Random();

    for(int i = 0; i < length; i++) {
      String charCategory = PASSWORD_DICTIONARY[random.nextInt(PASSWORD_DICTIONARY.length)];
      int position = random.nextInt(charCategory.length());
      password.append(charCategory.charAt(position));
    }
    return new String(password);
  }
436412
def generate_password(length=32):
    
    return ''.join(random.SystemRandom().choice(string.ascii_letters + '!@#$+.,') for _ in range(length))
579537
def token_gen_call(username, password):
    """"""
    secret_key = 'super-secret-key-please-change'
    mockusername = 'User2'
    mockpassword = 'Mypassword'
    if mockpassword == password and mockusername == username: # This is an example. Don't do that.
        return {"token" : jwt.encode({'user': username, 'data': 'mydata'}, secret_key, algorithm='HS256')}
    return 'Invalid username and/or password for user: {0}'.format(username)
300339
@Override
    public String generate(@Sensitive char[] password) {
        byte[] salt = generateSalt(generateSaltSize);
        byte[] outputBytes = generate(SUPPORTED_ALGORITHMS.get(generateAlgorithm), generateIterations, generateKeySize, salt, password);
        return format(SUPPORTED_ALGORITHMS.get(generateAlgorithm), generateIterations, salt, outputBytes);
    }
451149
public function preparePassword()
    {
        $this->{$this->securePasswordField} = crypt(
            $this->{$this->securePasswordField},
            '$2y$10$' . sha1(microtime() . $this->username . $this->email) . '$'
        );
    }
570031
function encryptPassword(password, callback) {
        bcrypt.gen_salt(workFactor, function(err, salt) {
            if (err) callback(err);
            
            bcrypt.encrypt(password, salt, function(err, hashedPassword) {
                if (err) callback(err);
                
                callback(null, hashedPassword);
            });
        });
    }
666668
def generate_secret
      if defined?(SecureRandom)
        SecureRandom.urlsafe_base64(32)
      else
        Base64.encode64(
          Digest::SHA256.digest("#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}")
        ).gsub('/','-').gsub('+','_').gsub('=','').strip
      end
    end
53054
def passwordLogin(self, username):
        
        self.challenge = secureRandom(16)
        self.username = username
        return {'challenge': self.challenge}
1285280
def generate_password_link(self):
        
        self.password_link = self.generate_hash(50)
        now = datetime.datetime.utcnow()
        self.password_link_expires = now + datetime.timedelta(hours=24)
694239
def pwgen(length=None):
    """"""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars))
970917
def mask_dict_password(dictionary, secret='***'):
    """"""
    d = dictionary.copy()
    for k in d:
        if 'password' in k:
            d[k] = secret
    return d
724495
def encrypt(self, password, kdf=None, iterations=None):
        '''
        
        '''
        return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iterations)
976720
async def authenticate(self, username: str, password: str) -> None:
        """"""
        self._credentials = {
            'username': username,
            'password': password,
        }

        await self._get_security_token()
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