Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getpasswd functionality in Go?

Situation:

I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?

What I tried:

I tried using syscall.Read, but it echoes what is typed.

like image 933
RogerV Avatar asked Jan 26 '10 03:01

RogerV


3 Answers

The following is one of best ways to get it done. First get term package by go get golang.org/x/term

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "syscall"

    "golang.org/x/term"
)

func main() {
    username, password, _ := credentials()
    fmt.Printf("Username: %s, Password: %s\n", username, password)
}

func credentials() (string, string, error) {
    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter Username: ")
    username, err := reader.ReadString('\n')
    if err != nil {
        return "", "", err
    }

    fmt.Print("Enter Password: ")
    bytePassword, err := term.ReadPassword(int(syscall.Stdin))
    if err != nil {
        return "", "", err
    }

    password := string(bytePassword)
    return strings.TrimSpace(username), strings.TrimSpace(password), nil
}

http://play.golang.org/p/l-9IP1mrhA

like image 182
gihanchanuka Avatar answered Nov 20 '22 06:11

gihanchanuka


Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass

It something like that:

package main

import "fmt"
import "github.com/howeyc/gopass"

func main() {
    fmt.Printf("Password: ")
    pass := gopass.GetPasswd()
    // Do something with pass
}
like image 30
Fatih Arslan Avatar answered Nov 20 '22 06:11

Fatih Arslan


Since Go ~v1.11 there is an official package golang.org/x/term which replaces the deprecated crypto/ssh/terminal. It has, among other things, the function term.ReadPassword.

Example usage:

package main
import (
    "fmt"
    "os"
    "syscall"
    "golang.org/x/term"
)
func main() {
    fmt.Print("Password: ")
    bytepw, err := term.ReadPassword(int(syscall.Stdin))
    if err != nil {
        os.Exit(1)
    }
    pass := string(bytepw)
    fmt.Printf("\nYou've entered: %q\n", pass)
}
like image 16
rustyx Avatar answered Nov 20 '22 06:11

rustyx