82 lines
1.2 KiB
Go
82 lines
1.2 KiB
Go
|
package scsusers
|
||
|
|
||
|
import (
|
||
|
"crypto/rand"
|
||
|
"encoding/base32"
|
||
|
"unicode"
|
||
|
)
|
||
|
|
||
|
func flipCoin() bool {
|
||
|
x := make([]byte, 1)
|
||
|
_, err := rand.Read(x)
|
||
|
if err != nil {
|
||
|
return true
|
||
|
}
|
||
|
if uint8(x[0]) % 2==0 {
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
|
||
|
}
|
||
|
func scrambleCase(in []byte) []byte {
|
||
|
var out []byte
|
||
|
for _, x := range string(in) {
|
||
|
if unicode.IsUpper(x) {
|
||
|
|
||
|
if flipCoin() {
|
||
|
out = append(out, byte(x))
|
||
|
} else {
|
||
|
out = append(out, byte(unicode.ToLower(x)))
|
||
|
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
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
|
||
|
}
|