mirror of
https://github.com/Luzifer/password.git
synced 2024-11-08 17:30:10 +00:00
Knut Ahlers
aa39ad3413
Squashed commit of the following: commit ef74c84e5b4826c2c58012cd4b0ea975d1dd7260 Author: Knut Ahlers <knut@ahlers.me> Date: Sun Dec 1 13:09:53 2019 +0100 Minor cleamup Signed-off-by: Knut Ahlers <knut@ahlers.me> commit 0b57aa8c8abb2fd118c71fdfd8d51cb707861821 Author: Knut Ahlers <knut@ahlers.me> Date: Sun Dec 1 13:09:17 2019 +0100 [#6] Add optional separator to XKCD passwords Signed-off-by: Knut Ahlers <knut@ahlers.me> Signed-off-by: Knut Ahlers <knut@ahlers.me>
58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package securepassword
|
|
|
|
import (
|
|
"errors"
|
|
"math/rand"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Luzifer/go_helpers/v2/str"
|
|
)
|
|
|
|
type XKCD struct {
|
|
// Separator to be used between words
|
|
Separator string
|
|
}
|
|
|
|
var (
|
|
// ErrTooFewWords represents an error thrown if the password will
|
|
// have fewer than four words and are not considered to be safe
|
|
ErrTooFewWords = errors.New("XKCD passwords with less than 4 words makes no sense")
|
|
// DefaultXKCD contains an default instance of the XKCD password
|
|
// generator
|
|
DefaultXKCD = NewXKCDGenerator()
|
|
)
|
|
|
|
// NewXKCDGenerator initializes a new XKCD password generator
|
|
// https://xkcd.com/936/
|
|
func NewXKCDGenerator() *XKCD { return &XKCD{} }
|
|
|
|
// GeneratePassword generates a password with the number of words
|
|
// given and optionally the current date prepended
|
|
func (x XKCD) GeneratePassword(length int, addDate bool) (string, error) {
|
|
if length < 4 {
|
|
return "", ErrTooFewWords
|
|
}
|
|
|
|
var (
|
|
password string
|
|
usedWords []string
|
|
)
|
|
|
|
if addDate {
|
|
password = time.Now().Format("20060102.")
|
|
}
|
|
|
|
rand.Seed(time.Now().UnixNano())
|
|
for len(usedWords) < length {
|
|
word := strings.Title(xkcdWordList[rand.Intn(len(xkcdWordList))])
|
|
if str.StringInSlice(word, usedWords) {
|
|
// Don't use a word twice
|
|
continue
|
|
}
|
|
|
|
usedWords = append(usedWords, word)
|
|
}
|
|
|
|
return password + strings.Join(usedWords, x.Separator), nil
|
|
}
|