password

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2023 License: Apache-2.0 Imports: 23 Imported by: 0

README

password - A password feature library wrote in golang.

Test Go Report Card GitHub go.mod Go version codecov Go Reference

Highlights

  • Validate password according options
  • Validate whether a password is common
  • Generate password according options
  • Encode & decode password according options
  • Verify password according options

Install

go get github.com/hunter007/password

Usage

0. Generate password
// 1. generate password via default config
p, _ := password.Generate(12, 4, 2, 1)

// 2. make a custom config. Any utf8 char is supported.
c := Config{
    UpperLetters: "壹贰叁肆伍陆柒捌玖拾",
    LowerLetters: "一二三四五六七八九十",
    Digits:       "①②③④⑤⑥⑦⑧⑨⑩0️⃣✅",
    Symbols:      "😭😁😄😞👏🏻🙋🏻‍♀️😴🔥",
}
g := NewGenerator(c)
p, _ := g.Generate(16, 4, 3, 0)
1. Validate password
// 1. setup ValidatorOption
voption := &ValidatorOption{
    MinLength: 6,
    MaxLength: 20,
    CommonPasswords: []string{"123456", "1qasw23ed"},
    RequireDigit: true,
    RequireLetter: true,
    RequirePunctuation: true,
}

// or use map
var voption ValidatorOption
config := map[string]interface{}{
    "min_length":          6,
    "max_length":          20,
    "common_passwords":    []string{"123456", "1qasw23ed"},
    "require_digit":       true,
    "require_letter":      true,
    "require_punctuation": true,
}
b, _ := json.Marshal(config)
err := json.Unmarshal(b, &voption)

// If CommonPasswords or CommonPasswordURL provided, password will be validated as common password.
// http request is sent by method `GET`, and response body will be as plain text, splited by "\n", one password one line.
voption.CommonPasswordURL = "http://xxx.com/pwd"

// don't forget to handle err
validator, _ := password.New(voption)

// 2. validate password
password := "user password"
err := validator.Validate(password)
if err != nil {
    // handle wrong password
}
2. Get hasher

Supported algorithm:

  • argon2id
  • bcrypt
  • bcrypt_sha256
  • md5
  • unsalted_md5
  • pbkdf2_sha1
  • pbkdf2_sha256
  • sha1
  • scrypt
// have a HasherOption
hoption := &HasherOption{
    Algorithm: "pbkdf2_sha256",
    Salt: "app salt",
    Iterations: 10000,
}

// or new HasherOption with map
option = map[string]interface{} {
    "algorithm": "pbkdf2_sha256",
    "secret": "secret",
    "salt": "app salt",
    "iterations": 10000,
}

b, _ := json.Marshal(option)
err := json.Unmarshal(b, &hoption)
if err != nil {
    // handle err
}

hasher, err := password.NewHasher(hoption)
if err != nil {
    // handle err
}
3. Encode password
password := "plaintext"
encoded, err := hasher.Encode(password)
if err != nil {
    // handle err
}
4. Decode password
pi, err := hasher.Decode(encoded)
if err != nil {
    // handle err
}
// pi contains algorithm, salt, iterations, etc.
5. Verify password
if !hasher.Verify(password, encoded) {
    // handle wrong password
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExceedsLength = errors.New("number of digits, symbols and upper letters must be less than total length")

Functions

func CryptoRandom added in v1.1.0

func CryptoRandom() int

CryptoRandom implemented by crypto/rand

func Generate added in v1.1.0

func Generate(length, minDigitLength, minSymbolLength, minUpperLetter uint) (string, error)

Generate generates password via default config:

LowerLetters: abcdefghijklmnopqrstuvwxyz
UpperLetters: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0123456789
Symbols: ~!@#$%^&*()_+`-={}|[]\\:\"<>?,./

func MathRandom added in v1.1.0

func MathRandom() int

MathRandom implemented by math/rand

func MustGenerate added in v1.1.0

func MustGenerate(length, minDigitLength, minSymbolLength, minUpperLetter uint) string

Generate generates password via default config, panic when error occcurred:

LowerLetters: abcdefghijklmnopqrstuvwxyz
UpperLetters: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0123456789
Symbols: ~!@#$%^&*()_+`-={}|[]\\:\"<>?,./

Types

type Argon2Params

type Argon2Params struct {
	// contains filtered or unexported fields
}

Argon2Params Argon2id parameters

type Config added in v1.1.0

type Config struct {
	// lower letters. any utf8 unicode supported.
	//
	// for example "一二三"
	LowerLetters string
	// upper letters. any utf8 unicode supported.
	//
	// for example "壹贰叁"
	UpperLetters string
	Digits       string
	Symbols      string
	// contains filtered or unexported fields
}

type Generator added in v1.1.0

type Generator interface {
	Generate(length, minDigitLength, minSymbolLength, minUpperLetter uint) (string, error)
	// MustGenerate like `Generate`, generates password.
	//
	// panic if errors occurred
	MustGenerate(length, minDigitLength, minSymbolLength, minUpperLetter uint) string
}

Generator provides methods which generates password.

all methods are goroutine-safe.

func NewGenerator added in v1.1.0

func NewGenerator(c Config) Generator

type Hasher

type Hasher interface {
	Encode(password string) (string, error)
	Decode(decoded string) (*PasswordInfo, error)
	Verify(password, encoded string) bool
	MustUpdate(encoded string) bool
	Harden(password, encoded string) (string, error)
}

func NewHasher

func NewHasher(opt *HasherOption) (Hasher, error)

type HasherOption

type HasherOption struct {
	// Algorithm: Support md5, unsalted_md5, pbkdf2_sha256, pbkdf2_sha1,
	// argon2id, bcrypt, bcrypt_sha256, scrypt, sha1
	Algorithm string `json:"algorithm"`

	Secret string `json:"secret"`

	// Salt: cannot contain '$'
	Salt string `json:"salt"`
	// Iterations: should be gratter than 0
	Iterations int         `json:"iterations"`
	Params     interface{} `json:"params"`
}

HasherOption Hasher option

func (*HasherOption) NewHasher

func (ho *HasherOption) NewHasher() (Hasher, error)

type PasswordInfo

type PasswordInfo struct {
	Algorithm  string
	Hash       string
	Iterations int
	Salt       string
	Others     interface{}
}

type RandomFunc added in v1.1.0

type RandomFunc func() int

type Validator

type Validator interface {
	// validates a password
	Validate(password string) error
}

Validator for validating password

func NewValidator

func NewValidator(opt *ValidatorOption) (Validator, error)

NewValidator return a Validator

type ValidatorOption

type ValidatorOption struct {
	// MinLength should be more than 0, and less than `MaxLength`
	MinLength uint8 `json:"min_length"`

	// MaxLength should be less than 32, and more than `MinLength`
	MaxLength uint8 `json:"max_length"`

	CommonPasswordURL string   `json:"common_password_url"`
	CommonPasswords   []string `json:"common_passwords"`

	RequireDigit       bool `json:"require_digit"`
	RequireLowercase   bool `json:"require_lowercase"`
	RequireUppercase   bool `json:"require_uppercase"`
	RequireLetter      bool `json:"require_letter"`
	RequirePunctuation bool `json:"require_punctuation"`
}

Validator option

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL