PWGen/pwgenerator/funcs.go

60 lines
1.1 KiB
Go
Raw Normal View History

2022-03-02 06:24:55 -05:00
package pwgenerator
import (
"bytes"
"crypto/rand"
"math/big"
2022-03-02 06:24:55 -05:00
"sort"
)
// sortDedupe sorts a slice of runes and deduplicates them.
func sortDedupe(charset *CharSet) {
var vals map[Char]bool = make(map[Char]bool)
var sorted CharSet
var idx int
// This inherently dedupes.
for _, i := range *charset {
vals[i] = true
}
// This handles sorting.
sorted = make(CharSet, len(vals))
// First we need a slice (again).
for k := range vals {
sorted[idx] = k
idx++
}
// And now we can sort...
sort.Sort(&sorted)
// And replace the original charset with the sorted, deduplicated one.
*charset = sorted
return
}
/*
saferRandInt uses crypto/rand instead of math/rand to get a random number.
While this is cryptographically safer, I guarantee it's a much bigger pain to do.
*/
func saferRandInt(max int) (randInt int, err error) {
var max64 int64 = int64(max)
var cryptoInt *big.Int = big.NewInt(max64)
var cryptoReader *bytes.Buffer = new(bytes.Buffer)
var randInt64 int64
if cryptoInt, err = rand.Int(cryptoReader, cryptoInt); err != nil {
return
}
randInt64 = cryptoInt.Int64()
randInt = int(randInt64)
return
}