Allow to read password when stdin is not a tty.

This commit is contained in:
Thorben Günther 2020-04-20 23:09:11 +02:00 committed by Simon Ser
parent 203dc3df6a
commit 1622b772ab

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"bufio"
"flag" "flag"
"fmt" "fmt"
"log" "log"
@ -54,12 +55,10 @@ func main() {
os.Exit(1) os.Exit(1)
} }
fmt.Printf("Password: ") password, err := readPassword()
password, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil { if err != nil {
log.Fatalf("failed to read password: %v", err) log.Fatalf("failed to read password: %v", err)
} }
fmt.Printf("\n")
hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil { if err != nil {
@ -80,12 +79,10 @@ func main() {
os.Exit(1) os.Exit(1)
} }
fmt.Printf("New password: ") password, err := readPassword()
password, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil { if err != nil {
log.Fatalf("failed to read new password: %v", err) log.Fatalf("failed to read password: %v", err)
} }
fmt.Printf("\n")
hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil { if err != nil {
@ -107,3 +104,29 @@ func main() {
} }
} }
} }
func readPassword() ([]byte, error) {
var password []byte
var err error
fd := int(os.Stdin.Fd())
if terminal.IsTerminal(fd) {
fmt.Printf("Password: ")
password, err = terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return nil, err
}
fmt.Printf("\n")
} else {
fmt.Fprintf(os.Stderr, "Warning: Reading password from stdin.\n")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
password = scanner.Bytes()
if len(password) == 0 {
return nil, fmt.Errorf("zero length password")
}
}
return password, nil
}