Browse Source

cryptoRand.Int / pseudoRand.Intn to generate random integer. Previous way was modulo-biased

pull/265/head
Leon Klingele 9 years ago committed by Simon Eisenmann
parent
commit
067ed1c3e3
  1. 28
      src/app/spreed-webrtc-server/random.go

28
src/app/spreed-webrtc-server/random.go

@ -23,6 +23,7 @@ package main @@ -23,6 +23,7 @@ package main
import (
"crypto/rand"
"math/big"
pseudoRand "math/rand"
"time"
)
@ -31,22 +32,25 @@ const ( @@ -31,22 +32,25 @@ const (
dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
func NewRandomString(length int) string {
func newRandomInt(max *big.Int) int {
rand, err := rand.Int(rand.Reader, max)
if err != nil {
// Fallback to pseudo-random
return pseudoRand.Intn(int(max.Int64()))
}
return int(rand.Int64())
}
// NewRandomString returns a alphanumeric random string with
// the specified length using crypto/rand with fallback to
// math/rand on error.
func NewRandomString(length int) string {
buf := make([]byte, length)
_, err := rand.Read(buf)
if err != nil {
// fallback to pseudo-random
for i := 0; i < length; i++ {
buf[i] = dict[pseudoRand.Intn(len(dict))]
}
} else {
for i := 0; i < length; i++ {
buf[i] = dict[int(buf[i])%len(dict)]
}
max := big.NewInt(int64(len(dict)))
for i := 0; i < length; i++ {
buf[i] = dict[newRandomInt(max)]
}
return string(buf)
}
func init() {

Loading…
Cancel
Save