scsusers/password.go

75 lines
1.2 KiB
Go

package scsusers
import (
"crypto/rand"
"encoding/base32"
"log"
mr "math/rand"
"time"
"unicode"
)
func flipCoin() bool {
r := mr.New(mr.NewSource(time.Now().UnixNano()))
return r.Intn(3) == 1
}
func scrambleCase(in []byte) []byte {
var out []byte
for _, x := range string(in) {
if unicode.IsUpper(x) && flipCoin() {
out = append(out, byte(unicode.ToLower(x)))
} else {
out = append(out, byte(x))
}
}
log.Printf("scrambleCase in %s out %s", in, out)
return out
}
func randBytes(n int) []byte {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
if err != nil {
panic(err)
}
return []byte(base32.StdEncoding.EncodeToString(randomBytes)[:n])
}
func generatePassword(n int) []byte {
for {
p := scrambleCase(randBytes(16))
if hasDigit(p) && hasUppercase(p) && hasLowercase(p) {
return p
}
}
}
func hasDigit(in []byte) bool {
for _, x := range string(in) {
if unicode.IsDigit(x) {
return true
}
}
return false
}
func hasUppercase(in []byte) bool {
for _, x := range string(in) {
if unicode.IsUpper(x) {
return true
}
}
return false
}
func hasLowercase(in []byte) bool {
for _, x := range string(in) {
if unicode.IsLower(x) {
return true
}
}
return false
}