Skip to content

Commit

Permalink
pkg/crypto: replace 'math/rand' with 'crypto/rand'
Browse files Browse the repository at this point in the history
  • Loading branch information
bb7133 committed Aug 28, 2024
1 parent b5bd3bb commit 8886a5c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 27 deletions.
55 changes: 29 additions & 26 deletions pkg/crypto/rand/rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,42 +14,45 @@
package rand

import (
cr "crypto/rand"
"encoding/binary"
"fmt"
"math/rand"
"crypto/rand"
"io"
"math/big"
)

var (
// Reader is a global random number source
Reader *rand.Rand
)
// rand provides a simple wrap of "crypto/rand".

func init() {
src := make([]byte, 8)
if _, err := cr.Read(src); err != nil {
panic(fmt.Sprintf("initial random: %s", err.Error()))
}
seed := binary.BigEndian.Uint64(src)
Reader = rand.New(rand.NewSource(int64(seed)))
// Reader is a global random number source
var Reader io.Reader = &cryptoRandReader{}

type cryptoRandReader struct{}

func (c *cryptoRandReader) Read(b []byte) (int, error) {
return rand.Read(b)
}

// Int wraps Rand.Int
// Int wraps Int63n
func Int() int {
return Reader.Int()
val := Int63n(int64(int(^uint(0) >> 1)))
return int(val)
}

// Intn wraps Rand.Intn
// Intn wraps Int63n
func Intn(n int) int {
return Reader.Intn(n)
if n <= 0 {
panic("argument to Intn must be positive")
}
val := Int63n(int64(n))
return int(val)
}

// Int63n wraps Rand.Int63n
// Int63n wraps rand.Int
func Int63n(n int64) int64 {
return Reader.Int63n(n)
}

// Read wraps Rand.Read
func Read(b []byte) (int, error) {
return Reader.Read(b)
if n <= 0 {
panic("argument to Int63n must be positive")
}
val, err := rand.Int(rand.Reader, big.NewInt(n))
if err != nil {
panic(err)
}
return val.Int64()
}
2 changes: 1 addition & 1 deletion pkg/telemetry/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
package telemetry

import (
"crypto/rand"
"fmt"
"os"
"path/filepath"

"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/pkg/crypto/rand"
"github.com/pingcap/tiup/pkg/environment"
"github.com/pingcap/tiup/pkg/localdata"
"github.com/pingcap/tiup/pkg/utils"
Expand Down

0 comments on commit 8886a5c

Please sign in to comment.