Browse Source

security fix: Use of insufficient randomness as the key of a cryptographic algorithm

mhsanaei 2 days ago
parent
commit
ae79b43cdb
1 changed files with 13 additions and 3 deletions
  1. 13 3
      util/random/random.go

+ 13 - 3
util/random/random.go

@@ -2,7 +2,8 @@
 package random
 
 import (
-	"math/rand"
+	"crypto/rand"
+	"math/big"
 )
 
 var (
@@ -40,12 +41,21 @@ func init() {
 func Seq(n int) string {
 	runes := make([]rune, n)
 	for i := 0; i < n; i++ {
-		runes[i] = allSeq[rand.Intn(len(allSeq))]
+		idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(allSeq))))
+		if err != nil {
+			panic("crypto/rand failed: " + err.Error())
+		}
+		runes[i] = allSeq[idx.Int64()]
 	}
 	return string(runes)
 }
 
 // Num generates a random integer between 0 and n-1.
 func Num(n int) int {
-	return rand.Intn(n)
+	bn := big.NewInt(int64(n))
+	r, err := rand.Int(rand.Reader, bn)
+	if err != nil {
+		panic("crypto/rand failed: " + err.Error())
+	}
+	return int(r.Int64())
 }