Skip to content

Commit

Permalink
Do not use global rand
Browse files Browse the repository at this point in the history
  • Loading branch information
emosbaugh committed Sep 3, 2020
1 parent 3073aa4 commit fe901e6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
11 changes: 8 additions & 3 deletions kotsadm/pkg/gitops/key.go
@@ -1,9 +1,10 @@
package gitops

import (
"crypto/rand"
"crypto/rsa"
"math/rand"
"sync"
"time"
)

var (
Expand All @@ -13,7 +14,11 @@ var (
preseedPrivateKeyMu sync.Mutex
)

var r *rand.Rand

func init() {
r = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))

go generatePreseedPrivateKey()
}

Expand All @@ -28,11 +33,11 @@ func getPrivateKey() (*rsa.PrivateKey, error) {
if key != nil {
return key, nil
}
return rsa.GenerateKey(rand.Reader, 4096)
return rsa.GenerateKey(r, 4096)
}

func generatePreseedPrivateKey() {
preseedPrivateKeyMu.Lock()
defer preseedPrivateKeyMu.Unlock()
preseedPrivateKey, _ = rsa.GenerateKey(rand.Reader, 4096)
preseedPrivateKey, _ = rsa.GenerateKey(r, 4096)
}
6 changes: 4 additions & 2 deletions kotsadm/pkg/rand/rand.go
Expand Up @@ -9,14 +9,16 @@ const LOWER_CASE = "abcdefghijklmnopqrstuvwxyz"
const UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const NUMERIC = "1234567890"

var r *rand.Rand

func init() {
rand.Seed(time.Now().UnixNano())
r = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
}

func StringWithCharset(length int, charset string) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
b[i] = charset[r.Intn(len(charset))]
}
return string(b)
}

0 comments on commit fe901e6

Please sign in to comment.