mirror of https://github.com/Xhofe/alist
feat(security): generating random string with crypto rand (#7525)
parent
150dcc2147
commit
12b429584e
|
@ -1,20 +1,27 @@
|
||||||
package random
|
package random
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math/rand"
|
"crypto/rand"
|
||||||
|
"math/big"
|
||||||
|
mathRand "math/rand"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Rand *rand.Rand
|
var Rand *mathRand.Rand
|
||||||
|
|
||||||
const letterBytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
const letterBytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
||||||
|
|
||||||
func String(n int) string {
|
func String(n int) string {
|
||||||
b := make([]byte, n)
|
b := make([]byte, n)
|
||||||
|
letterLen := big.NewInt(int64(len(letterBytes)))
|
||||||
for i := range b {
|
for i := range b {
|
||||||
b[i] = letterBytes[Rand.Intn(len(letterBytes))]
|
idx, err := rand.Int(rand.Reader, letterLen)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
b[i] = letterBytes[idx.Int64()]
|
||||||
}
|
}
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
@ -24,10 +31,10 @@ func Token() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func RangeInt64(left, right int64) int64 {
|
func RangeInt64(left, right int64) int64 {
|
||||||
return rand.Int63n(left+right) - left
|
return mathRand.Int63n(left+right) - left
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
s := rand.NewSource(time.Now().UnixNano())
|
s := mathRand.NewSource(time.Now().UnixNano())
|
||||||
Rand = rand.New(s)
|
Rand = mathRand.New(s)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue