henwen/back/genstring.go

28 lines
572 B
Go
Raw Normal View History

2020-04-01 06:35:15 +00:00
package back
import (
"bytes"
"crypto/rand"
"math/big"
)
var chars = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func SecureGenString(length int) (string, error) {
charsLength := big.NewInt(int64(len(chars)))
var maxN big.Int
maxN.Exp(charsLength, big.NewInt(int64(length)), nil)
n, err := rand.Int(rand.Reader, &maxN)
if err != nil {
return "", err
}
var buf bytes.Buffer
for n.Cmp(&big.Int{}) == 1 {
var charIdx big.Int
n.DivMod(n, charsLength, &charIdx)
_ = buf.WriteByte(chars[charIdx.Int64()])
}
return buf.String(), nil
}