Skip to content

Commit

Permalink
feat(security): generating random string with crypto rand (#7525)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mmx233 authored Nov 21, 2024
1 parent 150dcc2 commit 12b4295
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions pkg/utils/random/random.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
package random

import (
"math/rand"
"crypto/rand"
"math/big"
mathRand "math/rand"
"time"

"github.com/google/uuid"
)

var Rand *rand.Rand
var Rand *mathRand.Rand

const letterBytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func String(n int) string {
b := make([]byte, n)
letterLen := big.NewInt(int64(len(letterBytes)))
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)
}
Expand All @@ -24,10 +31,10 @@ func Token() string {
}

func RangeInt64(left, right int64) int64 {
return rand.Int63n(left+right) - left
return mathRand.Int63n(left+right) - left
}

func init() {
s := rand.NewSource(time.Now().UnixNano())
Rand = rand.New(s)
s := mathRand.NewSource(time.Now().UnixNano())
Rand = mathRand.New(s)
}

0 comments on commit 12b4295

Please sign in to comment.