Skip to content

Commit

Permalink
Merge pull request #439 from harshanarayana/hfx/convert/random-genera…
Browse files Browse the repository at this point in the history
…tor-to-use-crypto

envconf: use crypto/rand for random name generator
  • Loading branch information
k8s-ci-robot committed Jul 12, 2024
2 parents db6a005 + 1feb468 commit a8e494e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
11 changes: 7 additions & 4 deletions pkg/envconf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ limitations under the License.
package envconf

import (
"crypto/rand"
"encoding/hex"
"fmt"
"math/rand"
"regexp"
"time"

log "k8s.io/klog/v2"

Expand Down Expand Up @@ -303,9 +302,13 @@ func RandomName(prefix string, n int) string {
if len(prefix) >= n {
return prefix
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))

p := make([]byte, n)
r.Read(p)
_, err := rand.Read(p)
if err != nil {
log.ErrorS(err, "failed to generate random name. falling back to prefix directly")
return prefix
}
if prefix == "" {
return hex.EncodeToString(p)[:n]
}
Expand Down
12 changes: 12 additions & 0 deletions pkg/envconf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,15 @@ func TestRandomName(t *testing.T) {
}
})
}

func TestRandomGeneratorIsIndeedGeneratingRandom(t *testing.T) {
randomValues := make(map[string]int)
for attempt := 0; attempt < 10; attempt++ {
randomValues[RandomName("test-randomness", 32)]++
}
for key, val := range randomValues {
if val > 1 {
t.Errorf("random name %q was generated %d times", key, val)
}
}
}

0 comments on commit a8e494e

Please sign in to comment.