// GenerateFromPassword returns the hash of the password at the given cost.
// If the cost given is less than MinCost, the cost will be set to DefaultCost, instead.
351159
func (b *Bcrypt) GenerateFromPassword(password []byte, cost int) ([]byte, error) {
	if cost < bcrypt.MinCost {
		cost = DefaultCost
	}
	return bcrypt.GenerateFromPassword(password, cost)
}
1175570
func generateStoreLockName() string {
	h := sha256.New()
	h.Write([]byte(JujuControllersPath()))
	fullHash := fmt.Sprintf("%x", h.Sum(nil))
	return fmt.Sprintf("store-lock-%x", fullHash[:8])
}
811463
func (s ScryptAuth) Hash(pw_cost uint, user_password, salt []byte) (hash_ref []byte, err error) {
	scrypt_hash, err := scrypt.Key(user_password, salt, 1<<pw_cost, s.R, s.P, KEYLENGTH)
	if err != nil {
		return
	}
	hmac := hmac.New(sha256.New, s.HmacKey)
	if _, err = hmac.Write(scrypt_hash); err != nil {
		return
	}
	hash_ref = hmac.Sum(nil)
	return
}
938590
func (term *Terminal) Password(prefix string) (string, error) {
	var err error
	var input string

	for input == "" {
		input, err = term.GetPassword(prefix)
		if err != nil && err != io.EOF {
			return "", err
		}
	}

	return input, nil
}
1272890
func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) {
	id, err := GenerateRandomID()
	if err != nil {
		return "", fmt.Errorf("failed to generate ID: %s", err)
	}
	if whisper.HasSymKey(id) {
		return "", fmt.Errorf("failed to generate unique ID")
	}

	// kdf should run no less than 0.1 seconds on an average computer,
	// because it's an once in a session experience
	derived := pbkdf2.Key([]byte(password), nil, 65356, aesKeyLength, sha256.New)
	if err != nil {
		return "", err
	}

	whisper.keyMu.Lock()
	defer whisper.keyMu.Unlock()

	// double check is necessary, because deriveKeyMaterial() is very slow
	if whisper.symKeys[id] != nil {
		return "", fmt.Errorf("critical error: failed to generate unique ID")
	}
	whisper.symKeys[id] = derived
	return id, nil
}
586965
func GeneratePasswordCharsetCheck(length int, chars string) string {
	validator := crunchy.NewValidator()
	var password string

	for i := 0; i < 3; i++ {
		pw := &bytes.Buffer{}
		for pw.Len() < length {
			_ = pw.WriteByte(chars[randomInteger(len(chars))])
		}
		password = pw.String()

		if validator.Check(password) == nil {
			break
		}
	}

	return password
}
827375
func Password(p string) metaOp {
	return func(c *Client) {
		c.Password = strings.TrimSpace(p)
	}
}
1200114
func GeneratePassword(length int, symbols bool) string {
	chars := digits + upper + lower
	if symbols {
		chars += syms
	}
	if c := os.Getenv("GOPASS_CHARACTER_SET"); c != "" {
		chars = c
	}
	if c := os.Getenv("GOPASS_EXTERNAL_PWGEN"); c != "" {
		if pw, err := generateExternal(c); err == nil {
			return pw
		}
	}
	return GeneratePasswordCharsetCheck(length, chars)
}
648505
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) {
	// As noted in issue #10 and #17 this adds support for TOTP secrets that are
	// missing their padding.
	secret = strings.TrimSpace(secret)
	if n := len(secret) % 8; n != 0 {
		secret = secret + strings.Repeat("=", 8-n)
	}

	// As noted in issue #24 Google has started producing base32 in lower case,
	// but the StdEncoding (and the RFC), expect a dictionary of only upper case letters.
	secret = strings.ToUpper(secret)

	secretBytes, err := base32.StdEncoding.DecodeString(secret)
	if err != nil {
		return "", otp.ErrValidateSecretInvalidBase32
	}

	buf := make([]byte, 8)
	mac := hmac.New(opts.Algorithm.Hash, secretBytes)
	binary.BigEndian.PutUint64(buf, counter)
	if debug {
		fmt.Printf("counter=%v\n", counter)
		fmt.Printf("buf=%v\n", buf)
	}

	mac.Write(buf)
	sum := mac.Sum(nil)

	// "Dynamic truncation" in RFC 4226
	// http://tools.ietf.org/html/rfc4226#section-5.4
	offset := sum[len(sum)-1] & 0xf
	value := int64(((int(sum[offset]) & 0x7f) << 24) |
		((int(sum[offset+1] & 0xff)) << 16) |
		((int(sum[offset+2] & 0xff)) << 8) |
		(int(sum[offset+3]) & 0xff))

	l := opts.Digits.Length()
	mod := int32(value % int64(math.Pow10(l)))

	if debug {
		fmt.Printf("offset=%v\n", offset)
		fmt.Printf("value=%v\n", value)
		fmt.Printf("mod'ed=%v\n", mod)
	}

	return opts.Digits.Format(mod), nil
}
699176
func EncryptPasswordObject(ctx context.Context, password string, currentMasterKey *[]byte) (*primitive.UserPassword, *primitive.MasterKey, error) {
	pw := &primitive.UserPassword{
		Alg: Scrypt,
	}

	// Generate 128 bit (16 byte) salt for password
	salt := make([]byte, saltBytes) // 16
	_, err := rand.Read(salt)
	if err != nil {
		return nil, nil, err
	}

	// Encode salt bytes to base64url
	pw.Salt = base64.RawURLEncoding.EncodeToString(salt)

	// Create password hash bytes
	pwh, err := derivePassword(ctx, []byte(password), pw.Salt)
	if err != nil {
		return nil, nil, err
	}

	// Encode password value to base64url
	pw.Value = base64url.New(pwh)

	m, err := CreateMasterKeyObject(ctx, []byte(password), currentMasterKey)
	if err != nil {
		return nil, nil, err
	}

	return pw, m, nil
}
95263
func (s SecretForTLSGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	delegate := &SecretForTLSGeneratorV1{}
	hashParam, found := genericParams["append-hash"]
	if found {
		hashBool, isBool := hashParam.(bool)
		if !isBool {
			return nil, fmt.Errorf("expected bool, found :%v", hashParam)
		}
		delegate.AppendHash = hashBool
		delete(genericParams, "append-hash")
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate.Name = params["name"]
	delegate.Key = params["key"]
	delegate.Cert = params["cert"]
	return delegate.StructuredGenerate()
}
522355
func (sc *Client) GenerateSymmetricKeyFromPassword(ctx context.Context, passwd string) (string, error) {
	var id string
	return id, sc.c.CallContext(ctx, &id, "shh_generateSymKeyFromPassword", passwd)
}
134768
func GenerateKeypair() (pub string, priv string, err error) {
	var kp crypto.Keypair
	if err := kp.Generate(); err != nil {
		return "", "", err
	}
	return kp.PublicString(), kp.PrivateString(), nil
}
51788
func (s ScryptAuth) Gen(user_password []byte) (hash, salt []byte, err error) {
	salt = make([]byte, KEYLENGTH)
	salt_length, err := rand.Read(salt)
	if salt_length != KEYLENGTH {
		return nil, nil, errors.New("Insufficient random bytes for salt")
	}
	if err != nil {
		return nil, nil, err
	}

	hash, err = s.Hash(s.PwCost, user_password, salt)
	if err != nil {
		return nil, nil, err
	}
	return
}
1359301
func GenerateAddress(seed Trytes, index uint64, secLvl SecurityLevel, addChecksum ...bool) (Hash, error) {
	for len(seed)%81 != 0 {
		seed += "9"
	}

	if secLvl == 0 {
		secLvl = SecurityLevelMedium
	}

	subseed, err := Subseed(seed, index)
	if err != nil {
		return "", err
	}

	prvKey, err := Key(subseed, secLvl)
	if err != nil {
		return "", err
	}

	digests, err := Digests(prvKey)
	if err != nil {
		return "", err
	}

	addressTrits, err := Address(digests)
	if err != nil {
		return "", err
	}

	address := MustTritsToTrytes(addressTrits)

	if len(addChecksum) > 0 && addChecksum[0] {
		return checksum.AddChecksum(address, true, 9)
	}

	return address, nil
}
773826
func (s *Action) generatePassword(ctx context.Context, c *cli.Context, length string) (string, error) {
	if c.Bool("xkcd") || c.IsSet("xkcdsep") {
		return s.generatePasswordXKCD(ctx, c, length)
	}

	symbols := ctxutil.IsUseSymbols(ctx)
	if c.IsSet("symbols") {
		symbols = c.Bool("symbols")
	}

	var pwlen int
	if length == "" {
		candidateLength := defaultLength
		question := "How long should the password be?"
		iv, err := termio.AskForInt(ctx, question, candidateLength)
		if err != nil {
			return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
		}
		pwlen = iv
	} else {
		iv, err := strconv.Atoi(length)
		if err != nil {
			return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
		}
		pwlen = iv
	}

	if pwlen < 1 {
		return "", ExitError(ctx, ExitUsage, nil, "password length must not be zero")
	}

	corp, err := termio.AskForBool(ctx, "Do you have strict rules to include different character classes?", false)
	if err != nil {
		return "", err
	}
	if corp {
		return pwgen.GeneratePasswordWithAllClasses(pwlen)
	}

	return pwgen.GeneratePassword(pwlen, symbols), nil
}
987003
func GenerateSHA256PasswordHash(cleartext string) (string, error) {
	salt := make([]byte, saltSize)
	n, err := rand.Read(salt)
	if err != nil || n != saltSize {
		return "", errors.New("reading random bytes error")
	}

	hash := sha256.Sum256(append(salt, cleartext...))
	return sha256PasswordHashPrefix + passwordHashDivider +
		hex.EncodeToString(salt[:]) + passwordHashDivider +
		hex.EncodeToString(hash[:]), nil
}