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)
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)
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))
}
}
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
To support windows, as mentioned here, please use:
import "syscall"
import "golang.org/x/crypto/ssh/terminal"
passwd, err := terminal.ReadPassword(int(syscall.Stdin))
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
}