Browse Source

Merge branch 'leonklingele-fix-biased-rng' into develop

pull/265/head
Simon Eisenmann 9 years ago
parent
commit
8d1e18b007
  1. 3
      AUTHORS
  2. 30
      src/app/spreed-webrtc-server/random.go

3
AUTHORS

@ -6,6 +6,7 @@ @@ -6,6 +6,7 @@
Simon Eisenmann <simon@struktur.de>
Joachim Bauch <bauch@struktur.de>
Evan Theurer <theurer@struktur.de>
Leon Klingele <klingele@struktur.de>
Translation:
Curt Frisemo <curt.frisemo@spreed.com>
Curt Frisemo <curt.frisemo@spreed.com>

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

@ -23,30 +23,34 @@ package main @@ -23,30 +23,34 @@ package main
import (
"crypto/rand"
"math/big"
pseudoRand "math/rand"
"time"
)
const (
dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW0123456789"
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