• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang terminal.ReadPassword函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/ssh/terminal.ReadPassword函数的典型用法代码示例。如果您正苦于以下问题:Golang ReadPassword函数的具体用法?Golang ReadPassword怎么用?Golang ReadPassword使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ReadPassword函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Execute

func (x *cmdCreateKey) Execute(args []string) error {
	if len(args) > 0 {
		return ErrExtraArgs
	}

	keyName := x.Positional.KeyName
	if keyName == "" {
		keyName = "default"
	}
	if !asserts.IsValidAccountKeyName(keyName) {
		return fmt.Errorf(i18n.G("key name %q is not valid; only ASCII letters, digits, and hyphens are allowed"), keyName)
	}

	fmt.Fprint(Stdout, i18n.G("Passphrase: "))
	passphrase, err := terminal.ReadPassword(0)
	fmt.Fprint(Stdout, "\n")
	if err != nil {
		return err
	}
	fmt.Fprint(Stdout, i18n.G("Confirm passphrase: "))
	confirmPassphrase, err := terminal.ReadPassword(0)
	fmt.Fprint(Stdout, "\n")
	if err != nil {
		return err
	}
	if string(passphrase) != string(confirmPassphrase) {
		return errors.New("passphrases do not match")
	}
	if err != nil {
		return err
	}

	manager := asserts.NewGPGKeypairManager()
	return manager.Generate(string(passphrase), keyName)
}
开发者ID:niemeyer,项目名称:snapd,代码行数:35,代码来源:cmd_create_key.go


示例2: passwordPrompt

//passwordPrompt prompts user to enter password twice and that the two entries are equivalent.
func passwordPrompt() string {
	fmt.Print("Enter password: ")
	password, errs := terminal.ReadPassword(0)

	if errs != nil {
		fmt.Println("\nCould not read password:")
		log.Fatal(errs)
		os.Exit(1)
	}

	fmt.Print("\nConfirm password: ")
	passwordConfirm, errs := terminal.ReadPassword(0)

	if errs != nil {
		fmt.Println("\nCould Not read password.")
		log.Fatal(errs)
		os.Exit(1)
	}

	if reflect.DeepEqual(password, passwordConfirm) == false {
		fmt.Println("\n")
		log.Fatal("Passwords do not match")
	}

	return strings.TrimSpace(string(password))
}
开发者ID:dubsquared,项目名称:kumoru-cli,代码行数:27,代码来源:accounts.go


示例3: main

func main() {
	var pw = flag.Bool("p", false, "Input password via stdin")
	var cost = flag.Int("c", DefaultCost, "The cost weight, range of 4-31 (11)")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()

	var password string

	if *pw {
		fmt.Printf("Enter Password: ")
		bytePassword, _ := terminal.ReadPassword(0)
		fmt.Printf("\nReenter Password: ")
		bytePassword2, _ := terminal.ReadPassword(0)
		if !bytes.Equal(bytePassword, bytePassword2) {
			log.Fatalf("Error, passwords do not match\n")
		}
		password = string(bytePassword)
		fmt.Printf("\n")
	} else {
		password = genPassword()
		fmt.Printf("pass: %s\n", password)
	}

	cb, err := bcrypt.GenerateFromPassword([]byte(password), *cost)
	if err != nil {
		log.Fatalf("Error producing bcrypt hash: %v\n", err)
	}
	fmt.Printf("bcrypt hash: %s\n", cb)
}
开发者ID:tw4dl,项目名称:gnatsd,代码行数:31,代码来源:mkpasswd.go


示例4: promptForPassword

// promptForPassword prompts the user for a password twice, returning
// the read bytes if they match, or an error.
// It turns out getting non-echo stdin is tricky and not portable at all.
// terminal seems a decent solution, although it does not work on windows.
func promptForPassword() ([]byte, error) {
	// Use a raw terminal.
	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = terminal.Restore(0, oldState)
	}()

	fmt.Print("Enter password: ")
	one, err := terminal.ReadPassword(0)
	if err != nil {
		return nil, err
	}
	fmt.Print("\nConfirm password: ")
	two, err := terminal.ReadPassword(0)
	if err != nil {
		return nil, err
	}
	// Make sure stdout moves on to the next line.
	fmt.Print("\n")
	if !bytes.Equal(one, two) {
		return nil, util.Errorf("password mismatch")
	}
	return []byte(one), nil
}
开发者ID:kaustubhkurve,项目名称:cockroach,代码行数:31,代码来源:password.go


示例5: promptConsolePass

// promptConsolePass uses the given prefix to ask the user for a password.
// The function will ask the user to confirm the passphrase and will repeat
// the prompts until they enter a matching response.
func promptConsolePass(prefix string, confirm bool) ([]byte, error) {
	// Prompt the user until they enter a passphrase.
	prompt := fmt.Sprintf("%s: ", prefix)
	for {
		fmt.Print(prompt)
		pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			return nil, err
		}
		fmt.Print("\n")
		pass = bytes.TrimSpace(pass)
		if len(pass) == 0 {
			return nil, nil
		}

		if !confirm {
			return pass, nil
		}

		fmt.Print("Confirm passphrase: ")
		confirm, err := terminal.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			return nil, err
		}
		fmt.Print("\n")
		confirm = bytes.TrimSpace(confirm)
		if !bytes.Equal(pass, confirm) {
			fmt.Println("The entered passphrases do not match.")
			continue
		}

		return pass, nil
	}
}
开发者ID:DanielKrawisz,项目名称:bmagent,代码行数:37,代码来源:dbsetup.go


示例6: createNewVault

func createNewVault(path string, lowSecurity bool) {
	if !strings.HasSuffix(path, ".agilekeychain") {
		path += ".agilekeychain"
	}
	fmt.Printf("Creating new vault in %s\n", path)
	fmt.Printf("Enter master password: ")
	masterPwd, err := terminal.ReadPassword(0)
	fmt.Printf("\nRe-enter master password: ")
	masterPwd2, _ := terminal.ReadPassword(0)
	if !bytes.Equal(masterPwd, masterPwd2) {
		fatalErr(nil, "Passwords do not match")
	}

	security := onepass.VaultSecurity{MasterPwd: string(masterPwd)}
	if lowSecurity {
		// use fewer PBKDF2 iterations to speed up
		// master key decryption
		security.Iterations = 10
	}

	_, err = onepass.NewVault(path, security)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to create new vault: %v", err)
	}
}
开发者ID:robertknight,项目名称:1pass,代码行数:25,代码来源:client.go


示例7: InputNewPassword

func InputNewPassword(uname string) []byte {
	fmt.Printf("creating password for user %s\n", uname)
	for true {
		fmt.Print("\nInput your password:")
		upass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			fmt.Println("\nInvalid input!")
			continue
		}
		fmt.Print("\nType the password again:")
		pass2, err := terminal.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			fmt.Println("\nInvalid input!")
			continue
		}
		if !bytes.Equal(upass, pass2) {
			fmt.Println("\nTwo typing are not equal!")
			continue
		}
		if GoodPass(upass) {
			fmt.Println("\n")
			return upass
		} else {
			fmt.Println("\nNot a good password!")
		}
	}
	fmt.Println("\n")
	return nil
}
开发者ID:hujun-open,项目名称:manpass,代码行数:29,代码来源:common.go


示例8: setDatabasePw

func setDatabasePw() {
	fmt.Println("Please type password for database: ")
	pw, _ := terminal.ReadPassword(0)
	ans := string(pw)
	switch ans {
	case "":
		newConf.DatabasePassword = config.DatabasePassword
	case "q":
		fmt.Println("Terminating..")
		os.Exit(0)
	case "b":
		if functionIndex > 0 {
			functionIndex--
		}
		return
	default:
		fmt.Println("Type again to confirm: ")
		confirm, _ := terminal.ReadPassword(0)
		if ans != string(confirm) {
			fmt.Println("Passwords does not match, try again")
			return
		}

		newConf.DatabasePassword = ans
	}
	functionIndex++
}
开发者ID:eeayiaia,项目名称:scmt,代码行数:27,代码来源:init.go


示例9: Key

// Key will return a 32 byte key from a key phrase, cache, or prompting the
// user. If any of the func args are "", that procedure will be skipped. In the
// OS environment, x_KEY x_KEY_FILE and x_KEY_INACTIVITY are used for the key
// phrase itself (not recommended), where to cache, and for how long.
func Key(phrase string, envPrefix string, prompt string, confirm string) ([]byte, error) {
	if phrase != "" {
		return keyPhrase(phrase), nil
	}
	if envPrefix != "" {
		if phrase = os.Getenv(envPrefix + "_KEY"); phrase != "" {
			return keyPhrase(phrase), nil
		}
		fname := os.Getenv(envPrefix + "_KEY_FILE")
		if fname != "" {
			if inact, err := strconv.Atoi(os.Getenv(envPrefix + "_KEY_INACTIVITY")); err == nil && inact > 0 {
				if finfo, err := os.Stat(fname); err == nil && finfo.Size() == 32 && finfo.Mode() == 0600 && time.Now().After(finfo.ModTime()) && time.Now().Sub(finfo.ModTime()).Seconds() < float64(inact) {
					if key, err := ioutil.ReadFile(fname); err == nil && len(key) == 32 {
						return key, nil
					}
				}
			}
			os.Remove(fname)
		}
	}
	if prompt == "" {
		return nil, NoKeyAndNoPromptError
	}
	tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0600)
	if err != nil {
		return nil, fmt.Errorf("no controlling terminal to ask for key phrase: %s", err)
	}
	var bphrase []byte
	if _, err = fmt.Fprintf(tty, prompt); err != nil {
		return nil, err
	}
	if bphrase, err = terminal.ReadPassword(int(tty.Fd())); err != nil {
		return nil, err
	}
	if _, err = fmt.Fprintf(tty, "\n"); err != nil {
		return nil, err
	}
	if confirm != "" {
		if _, err = fmt.Fprintf(tty, confirm); err != nil {
			return nil, err
		}
		var bphrase2 []byte
		if bphrase2, err = terminal.ReadPassword(int(tty.Fd())); err != nil {
			return nil, err
		}
		if _, err = fmt.Fprintf(tty, "\n"); err != nil {
			return nil, err
		}
		if !bytes.Equal(bphrase, bphrase2) {
			return nil, fmt.Errorf("input did not match")
		}
	}
	if bphrase == nil || len(bphrase) == 0 {
		return nil, fmt.Errorf("empty input")
	}
	return keyPhrase(string(bphrase)), nil
}
开发者ID:csakshaug,项目名称:brimcrypt,代码行数:61,代码来源:key.go


示例10: doAddPassword

func doAddPassword(args []string) error {
	var plaintext []byte
	var err error

	if len(args) == 1 && terminal.IsTerminal(0) {
		fmt.Printf("Contents for password `%s': ", args[0])
		plaintext, err = terminal.ReadPassword(0)
		if err != nil {
			return err
		}
		fmt.Println()
	} else {
		var f io.Reader
		if len(args) > 1 {
			file, err := os.Open(args[1])
			if err != nil {
				return err
			}
			defer file.Close()
			f = file
		} else {
			f = os.Stdin
		}
		if plaintext, err = ioutil.ReadAll(f); err != nil {
			return err
		}
	}

	if err = config.WritePassword(args[0], string(plaintext)); err != nil {
		return err
	}

	fmt.Printf("Saved password `%s'\n", args[0])
	return nil
}
开发者ID:nelhage,项目名称:pw,代码行数:35,代码来源:commands.go


示例11: readPassword

// TODO(axw) this is now in three places: change-password,
// register, and here. Refactor and move to a common location.
func readPassword(stdin io.Reader) (string, error) {
	if f, ok := stdin.(*os.File); ok && terminal.IsTerminal(int(f.Fd())) {
		password, err := terminal.ReadPassword(int(f.Fd()))
		return string(password), err
	}
	return readLine(stdin)
}
开发者ID:bac,项目名称:juju,代码行数:9,代码来源:base.go


示例12: main

func main() {
	r := bufio.NewReader(os.Stdin)
	fmt.Print("GitHub Username: ")
	username, _ := r.ReadString('\n')

	fmt.Print("GitHub Password: ")
	bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
	password := string(bytePassword)

	tp := github.BasicAuthTransport{
		Username: strings.TrimSpace(username),
		Password: strings.TrimSpace(password),
	}

	client := github.NewClient(tp.Client())
	user, _, err := client.Users.Get("")

	// Is this a two-factor auth error?  If so, prompt for OTP and try again.
	if _, ok := err.(*github.TwoFactorAuthError); err != nil && ok {
		fmt.Print("\nGitHub OTP: ")
		otp, _ := r.ReadString('\n')
		tp.OTP = strings.TrimSpace(otp)
		user, _, err = client.Users.Get("")
	}

	if err != nil {
		fmt.Printf("\nerror: %v\n", err)
		return
	}

	fmt.Printf("\n%v\n", github.Stringify(user))
}
开发者ID:dindinet,项目名称:go-github,代码行数:32,代码来源:main.go


示例13: readPassword

func readPassword(prompt string) (string, error) {
	fmt.Fprintf(os.Stderr, prompt)

	tty, err := os.Open("/dev/tty")
	if err != nil {
		return "", hierr.Errorf(
			err,
			`TTY is required for reading password, `+
				`but /dev/tty can't be opened`,
		)
	}

	password, err := terminal.ReadPassword(int(tty.Fd()))
	if err != nil {
		return "", hierr.Errorf(
			err,
			`can't read password`,
		)
	}

	if prompt != "" {
		fmt.Fprintln(os.Stderr)
	}

	return string(password), nil
}
开发者ID:reconquest,项目名称:orgalorg,代码行数:26,代码来源:main.go


示例14: Prompt

// Prompt displays a prompt and returns answer
func (p *Prompter) Prompt() string {
	fmt.Print(p.msg())
	if p.UseDefault || skip() {
		return p.Default
	}
	input := ""
	if p.NoEcho {
		b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
		if err == nil {
			input = string(b)
		}
		fmt.Print("\n")
	} else {
		scanner := bufio.NewScanner(os.Stdin)
		ok := scanner.Scan()
		if ok {
			input = strings.TrimRight(scanner.Text(), "\r\n")
		}
	}
	if input == "" {
		input = p.Default
	}
	if !p.inputIsValid(input) {
		fmt.Println(p.errorMsg())
		return p.Prompt()
	}
	return input
}
开发者ID:tkuchiki,项目名称:prompter,代码行数:29,代码来源:prompter.go


示例15: getPassword

func getPassword() ([]byte, error) {
	signals := make(chan os.Signal, 1)
	passwords := make(chan password)
	signal.Notify(signals, os.Interrupt, os.Kill)
	defer signal.Stop(signals)
	state, err := terminal.GetState(2)
	if err != nil {
		return nil, err
	}
	defer terminal.Restore(2, state)
	go func() {
		fmt.Fprintf(os.Stderr, "Password: ")
		defer fmt.Fprintf(os.Stderr, "\n")
		p, err := terminal.ReadPassword(2)
		passwords <- password{
			Password: p,
			Err:      err,
		}
		close(passwords)
	}()
	select {
	case <-signals:
		return nil, fmt.Errorf("Password entry cancelled")
	case password := <-passwords:
		return password.Password, password.Err
	}
}
开发者ID:zennro,项目名称:oyster,代码行数:27,代码来源:main.go


示例16: main

func main() {
	r := bufio.NewReader(os.Stdin)

	fmt.Print("JIRA base URL (ex.: https://me.atlassian.net): ")
	baseurl, _ := r.ReadString('\n')

	fmt.Print("JIRA Username: ")
	username, _ := r.ReadString('\n')

	fmt.Print("JIRA Password: ")
	bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
	password := string(bytePassword)

	tp := jira.BasicAuthTransport{
		Username: strings.TrimSpace(username),
		Password: strings.TrimSpace(password),
	}

	client, _ := jira.NewClient(tp.Client(), strings.TrimSpace(baseurl))

	fmt.Print("\nIssue key (ex.: TEST-1): ")
	key, _ := r.ReadString('\n')

	issue, _, err := client.Issue.Get(strings.TrimSpace(key))
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s: %+v\n", issue.Key, issue.Fields.Summary)
}
开发者ID:rumyantseva,项目名称:go-jira,代码行数:30,代码来源:main.go


示例17: readLine

func readLine(w io.Writer, r io.Reader, secret bool) ([]byte, error) {
	if f, ok := r.(*os.File); ok && secret && terminal.IsTerminal(int(f.Fd())) {
		defer w.Write([]byte{'\n'})
		return terminal.ReadPassword(int(f.Fd()))
	}
	var input []byte
	for {
		var buf [1]byte
		n, err := r.Read(buf[:])
		if n == 1 {
			if buf[0] == '\n' {
				break
			}
			input = append(input, buf[0])
		}
		if err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return nil, errgo.Mask(err)
		}
	}
	if len(input) > 0 && input[len(input)-1] == '\r' {
		input = input[:len(input)-1]
	}
	return input, nil
}
开发者ID:cmars,项目名称:oo,代码行数:27,代码来源:form.go


示例18: GetPaste

// Get paste from api by passing slug
// Will prompt password if paste is encrypted
func GetPaste(slug string) string {
	url := "https://vvt.nu/" + slug + ".json"
	result, err := http.Get(url)

	if err != nil {
		panic(err)
	}

	defer result.Body.Close()

	body, err := ioutil.ReadAll(result.Body)
	if err != nil {
		panic(err)
	}
	paste := decodeJSON(body)

	// Move this logix out of GetPaste..
	if paste.Encrypted == true {
		fmt.Printf("This paste is encrypted, enter password: ")
		password, err := terminal.ReadPassword(0)
		if err != nil {
			panic(err)
		}

		fmt.Print("\n")

		content, err := Decrypt(paste.Code, string(password))
		if err != nil {
			panic(err)
		}
		return content
	}

	return paste.Code
}
开发者ID:rendom,项目名称:vvt-cli,代码行数:37,代码来源:vvt.go


示例19: UserLogin

//Prompt user for login and auth with
//acquire auth token
func (cli *CLI) UserLogin() {
	//get username or password
	var identity string
	fmt.Fprintf(os.Stderr, "Please enter your username or email: ")
	_, err := fmt.Scanln(&identity)
	check(err)

	//get password
	fmt.Fprintf(os.Stderr, "Please enter your password: ")
	pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
	fmt.Fprintf(os.Stderr, "\n")
	check(err)
	password := string(pass)

	//determine if given username or password
	var auth User
	if strings.ContainsRune(identity, '@') {
		auth = User{Email: identity, Password: password}
	} else {
		auth = User{Username: identity, Password: password}
	}

	token, err := cli.Client.UserLogin(auth)
	check(err)

	cli.Client.Auth = token
	cli.save()
}
开发者ID:csquared,项目名称:canvas-cli,代码行数:30,代码来源:cli.go


示例20: checkForAuth

// Checks for authentication flags and returns a username/password
// from the specified settings
func checkForAuth(ctx *cli.Context) (username, password string) {
	if ctx.IsSet("password") {
		username = "snap" // for now since username is unused but needs to exist for basicAuth
		// Prompt for password
		fmt.Print("Password:")
		pass, err := terminal.ReadPassword(0)
		if err != nil {
			password = ""
		} else {
			password = string(pass)
		}
		// Go to next line after password prompt
		fmt.Println()
		return
	}
	//Get config file path in the order:
	if ctx.IsSet("config") {
		cfg := &config{}
		if err := cfg.loadConfig(ctx.String("config")); err != nil {
			fmt.Println(err)
		}
		if cfg.RestAPI.Password != nil {
			password = *cfg.RestAPI.Password
		} else {
			fmt.Println("Error config password field 'rest-auth-pwd' is empty")
		}
	}
	return
}
开发者ID:callidetech,项目名称:snap,代码行数:31,代码来源:main.go



注:本文中的golang.org/x/crypto/ssh/terminal.ReadPassword函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang terminal.Restore函数代码示例发布时间:2022-05-28
下一篇:
Golang terminal.NewTerminal函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap