17 Commits
Author SHA1 Message Date
RandyTheSilly f70ff83e1e Add rune input functions 2026-05-29 21:02:04 -04:00
RandyTheSilly 2fe21452c7 Bump dependencies & drop web package 2026-05-29 19:38:12 -04:00
RandyTheSilly 687518a0a6 Bump dependencies 2026-04-01 00:09:34 -04:00
RandyTheSilly 8313a183b0 Add web package 2026-04-01 00:08:39 -04:00
RandyTheSilly 7a63a41116 Make WriteToStdin input zeroization optional 2026-02-14 16:50:35 -05:00
RandyTheSilly b7a2ae3378 Remove (maybe temporarily) Windows-specific input functions 2026-02-13 17:26:28 -05:00
RandyTheSilly 26686374bd Avoid compiler optimizations breaking ZeroizeBytes 2026-02-10 22:16:48 -05:00
RandyTheSilly 29315c4b76 Rename InputHidden to InputSecret 2026-02-10 20:30:46 -05:00
RandyTheSilly 48e6abea8b Harden functions that potentially deal with sensitive information 2026-02-09 22:15:47 -05:00
RandyTheSilly e1bb0012a7 Add secure byte slice erase helper; add alternative input methods for Windows 2026-02-07 22:54:02 -05:00
RandyTheSilly 9ee213eeb4 Print blank line after invalid input in front.InputInt 2026-01-08 23:03:28 -05:00
RandyTheSilly cc379d407c Re-instate prepended new line for prompt in InputMenuGen 2026-01-08 22:25:41 -05:00
RandyTheSilly c61aa7b720 Update copyright date 2026-01-08 21:46:43 -05:00
RandyTheSilly 6201774a15 Do not automatically prepend new line to input function prompts 2026-01-08 21:46:19 -05:00
RandyTheSilly 03e6942724 Bump dependencies 2026-01-07 20:05:49 -05:00
RandyTheSilly df1fb21b23 Add StringGen() for generating cryptographically secure strings 2025-12-11 12:14:53 -05:00
RandyTheSilly 10ee4f91fc Add ANSI constants for warning/blue/green 2025-11-10 00:50:16 -05:00
10 changed files with 199 additions and 76 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2025 Randall Winkhart
Copyright (c) 2025-2026 Randall Winkhart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+6 -3
View File
@@ -5,9 +5,12 @@ import "os"
var Home, _ = os.UserHomeDir()
const (
AnsiBold = "\033[1m"
AnsiError = "\033[38;5;9m"
AnsiReset = "\033[0m"
AnsiBold = "\033[1m"
AnsiError = "\033[38;5;9m"
AnsiWarning = "\033[38;5;3m"
AnsiBlue = "\033[38;5;4m"
AnsiGreen = "\033[38;5;2m"
AnsiReset = "\033[0m"
ErrorRead = 101
ErrorWrite = 102
+12 -7
View File
@@ -6,10 +6,12 @@ import (
"io"
"os"
"os/exec"
"github.com/rwinkhart/go-boilerplate/security"
)
// WriteToStdin is a utility function that writes a string to a command's stdin.
func WriteToStdin(cmd *exec.Cmd, input string) error {
// WriteToStdin is a utility function that writes a byte slice to a command's stdin.
func WriteToStdin(cmd *exec.Cmd, input []byte, zeroizeInput bool) error {
stdin, err := cmd.StdinPipe()
if err != nil {
return errors.New("unable to access stdin for system command: " + err.Error())
@@ -18,16 +20,19 @@ func WriteToStdin(cmd *exec.Cmd, input string) error {
defer func(stdin io.WriteCloser) {
_ = stdin.Close() // error ignored; if stdin could be accessed, it can probably be closed
}(stdin)
_, _ = io.WriteString(stdin, input)
_, _ = stdin.Write(input)
if zeroizeInput {
security.ZeroizeBytes(input)
}
}()
return nil
}
// ReadFromStdin is a utility function that reads a string from stdin.
func ReadFromStdin() string {
// ReadFromStdin is a utility function that reads a byte slice from stdin.
func ReadFromStdin() []byte {
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
return scanner.Text()
return scanner.Bytes()
}
return ""
return nil
}
-58
View File
@@ -1,58 +0,0 @@
package front
import (
"bufio"
"fmt"
"os"
"strings"
"golang.org/x/term"
)
// Input prompts the user for input and returns the input as a string.
func Input(prompt string) string {
fmt.Print("\n" + prompt + " ")
reader := bufio.NewReader(os.Stdin)
userInput, _ := reader.ReadString('\n')
return strings.TrimRight(userInput, "\n\r ") // remove trailing newlines, carriage returns, and spaces
}
// InputHidden prompts the user for input and returns the input as a byte array, hiding the input from the terminal.
func InputHidden(prompt string) []byte {
fmt.Print("\n" + prompt + " ")
byteInput, _ := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return byteInput
}
// InputBinary prompts the user with a yes/no question and returns the response as a boolean.
func InputBinary(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print("\n" + prompt + " (y/N) ")
char, _, _ := reader.ReadRune()
if char == 'y' || char == 'Y' {
return true
}
return false
}
// InputInt prompts the user for input and returns the input as an integer.
// A negative min/max value will disable the respective limit.
func InputInt(prompt string, min, max int) int {
for {
fmt.Print("\n" + prompt + " ")
var userInput int
_, err := fmt.Scanln(&userInput)
if err == nil && (userInput >= min || min < 0) && (userInput <= max || max < 0) {
return userInput
}
}
}
// InputMenuGen prompts the user with a menu and returns the user's choice as an integer.
func InputMenuGen(prompt string, options []string) int {
for i, option := range options {
fmt.Printf("%d. %s\n", i+1, option)
}
return InputInt(prompt, 1, len(options))
}
+52
View File
@@ -0,0 +1,52 @@
package front
import (
"bufio"
"fmt"
"os"
"strings"
)
// Input prompts the user for input and
// returns the input as a string.
func Input(prompt string) string {
fmt.Print(prompt + " ")
reader := bufio.NewReader(os.Stdin)
userInput, _ := reader.ReadString('\n')
return strings.TrimRight(userInput, "\n\r ") // remove trailing newlines, carriage returns, and spaces
}
// Input prompts the user for input and
// returns the input as a rune.
func InputRune(prompt string) rune {
fmt.Print(prompt + " ")
reader := bufio.NewReader(os.Stdin)
userInput, _, _ := reader.ReadRune()
return userInput
}
// InputBinary prompts the user with a yes/no
// question and returns the response as a boolean.
func InputBinary(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt + " (y/N) ")
char, _, _ := reader.ReadRune()
if char == 'y' || char == 'Y' {
return true
}
return false
}
// InputInt prompts the user for input and returns the input as an integer.
// A negative min/max value will disable the respective limit.
func InputInt(prompt string, min, max int) int {
for {
fmt.Print(prompt + " ")
var userInput int
_, err := fmt.Scanln(&userInput)
if err == nil && (userInput >= min || min < 0) && (userInput <= max || max < 0) {
return userInput
}
fmt.Println()
}
}
+43
View File
@@ -0,0 +1,43 @@
package front
import (
"fmt"
"os"
"slices"
"golang.org/x/term"
)
// InputMenuGen prompts the user with a menu
// and returns the user's choice as an integer.
func InputMenuGen(prompt string, options []string) int {
for i, option := range options {
fmt.Printf("%d. %s\n", i+1, option)
}
return InputInt("\n"+prompt, 1, len(options))
}
// InputMenuGenWithRuneInputs prompts the user with a menu
// and returns the user's choice as a rune.
// Ensure runeInputs contains only unique runes and matches the
// length of options.
func InputMenuGenWithRuneInputs(prompt string, options []string, runeInputs []rune) rune {
for i, option := range options {
fmt.Printf("%c. %s\n", runeInputs[i], option)
}
for {
userInput := InputRune("\n" + prompt)
if slices.Contains(runeInputs, userInput) {
return userInput
}
}
}
// InputSecret prompts the user for input and returns the
// input as a byte array, hiding the input from the terminal.
func InputSecret(prompt string) []byte {
fmt.Print(prompt + " ")
byteInput, _ := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return byteInput
}
+3 -3
View File
@@ -1,7 +1,7 @@
module github.com/rwinkhart/go-boilerplate
go 1.24.3
go 1.26.3
require golang.org/x/term v0.32.0
require golang.org/x/term v0.43.0
require golang.org/x/sys v0.33.0 // indirect
require golang.org/x/sys v0.45.0 // indirect
+4 -4
View File
@@ -1,4 +1,4 @@
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
+67
View File
@@ -0,0 +1,67 @@
package security
import (
"bytes"
"crypto/rand"
"fmt"
"math"
"math/big"
)
// BytesGen generates a random byte slice of a specified length and complexity.
// Requires: complexity (minimum percentage of special characters to be returned in the generated output; set to 0 for a "simple" result),
// complexCharsetLevel (1 = safe for filenames, 2 = safe for most password entries, 3 = safe only for well-made password entries)
func BytesGen(length int, complexity float64, complexCharsetLevel uint8) []byte {
var actualSpecialChars int // track the number of special characters in the generated output
var minSpecialChars int // track the minimum number of special characters to accept
var extendedCharset string // additions to character set used for complex outputs
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // default character set used for all strings
const extendedCharsetFiles = "!#$%&+,-.;=@_~^()[]{}`'" // additional special characters for complex strings (safe in file names)
const extendedCharsetMostPassword = "*:><?|" // additional special characters for complex strings (NOT safe in file names)
const extendedCharsetSpecialPassword = "\"/\\" // additional special characters for complex strings (NOT safe in file names)
if complexity > 0 {
minSpecialChars = int(math.Round(float64(length) * complexity)) // determine minimum number of special characters to accept
switch complexCharsetLevel {
case 1:
extendedCharset = extendedCharsetFiles
case 2:
extendedCharset = extendedCharsetMostPassword + extendedCharsetFiles[:len(extendedCharsetFiles)-9]
case 3:
extendedCharset = extendedCharsetFiles + extendedCharsetMostPassword + extendedCharsetSpecialPassword
}
charset += extendedCharset
}
// loop until a byte slice of the desired complexity is generated
for {
// generate a random output
result := make([]byte, length)
for i := range result {
val, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
result[i] = charset[val.Int64()]
}
// return early if the desired output is not complex
if complexity <= 0 {
return result
}
// count the number of special characters in the generated output
for i := range result {
if bytes.Contains([]byte(extendedCharset), []byte{result[i]}) {
actualSpecialChars++
}
}
// return the generated output if it contains enough special characters
if actualSpecialChars >= minSpecialChars {
return result
}
// reset special character counter
fmt.Println("Regenerating output until desired complexity is achieved...")
actualSpecialChars = 0
}
}
+11
View File
@@ -0,0 +1,11 @@
package security
// ZeroizeBytes overwrites all
// bytes in a slice with zeros.
//
//go:noinline
func ZeroizeBytes(input []byte) {
for i := range input {
input[i] = 0
}
}