28 lines
572 B
Go
28 lines
572 B
Go
|
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
|
||
|
}
|