6

How do I hide user input (password field) in terminal similar to the -s command in read -s p "password " password in bash. ?

var password string
fmt.Println("password: ")
fmt.Scan(&password)

http://play.golang.org/p/xAPDDPjKb4

user3918985
  • 4,278
  • 9
  • 42
  • 63
  • 1
    possible duplicate of [getpasswd functionality in Go?](http://stackoverflow.com/questions/2137357/getpasswd-functionality-in-go) – Salvador Dali May 21 '15 at 03:13

4 Answers4

17

The best way would be to use ReadPassword() from the terminal package. Else you can also look in this question for more ways to do so.

Code example:

package main

import "golang.org/x/crypto/ssh/terminal"
import "fmt"

func main() {
 fmt.Println("Enter password: ")
 password, err := terminal.ReadPassword(0)
 if err == nil {
    fmt.Println("Password typed: " + string(password))
 }
}
Community
  • 1
  • 1
Bhullnatik
  • 1,263
  • 17
  • 28
4

I have no idea about go, so I'm not sure if you can call other programs. If so, just call stty -echo to hide input and stty echo to show it again.

Otherwise you could try the following:

fmt.Println("password: ")
fmt.Println("\033[8m") // Hide input
fmt.Scan(&password)
fmt.Println("\033[28m") // Show input
Ignasi
  • 732
  • 4
  • 23
4

To support windows, as mentioned here, please use:

import "syscall"
import "golang.org/x/crypto/ssh/terminal"

passwd, err := terminal.ReadPassword(int(syscall.Stdin))
0

I tried a couple of different methods for this and found issues (e.g. Ctrl+C not breaking out of the program if it's waiting for a password).

This is how I got it working in the end - this works perfectly in OSX. Haven't tried in other environments:

import (

    "log"
    "code.google.com/p/go.crypto/ssh/terminal"
    "github.com/seehuhn/password"

)

func StringPrompt() (password string, err error) {
    state, err := terminal.MakeRaw(0)
    if err != nil {
        log.Fatal(err)
    }
    defer terminal.Restore(0, state)
    term := terminal.NewTerminal(os.Stdout, "")
    password, err = term.ReadLine()
    if err != nil {
        log.Fatal(err)
    }
    return
}
David Brophy
  • 849
  • 9
  • 19