use rand.Seed to seed the random function generator

This commit is contained in:
Tak Wai Wong 2022-06-09 13:02:18 -07:00
parent d017f8c3ec
commit e40f9bb7f0

View file

@ -1,15 +1,13 @@
package config package config
import ( import (
"encoding/base64"
"math/rand" "math/rand"
"regexp" "time"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
) )
var nonceByteLength = 32 var nonceLength = 32
var minNonceCharacterLength = 8
type AuthParams interface { type AuthParams interface {
GetParams() interface{} GetParams() interface{}
@ -26,7 +24,7 @@ func (p EthereumAuthParams) GetParams() interface{} {
copyP := p copyP := p
copyP.ChainIDs = make([]int, len(p.ChainIDs)) copyP.ChainIDs = make([]int, len(p.ChainIDs))
copy(copyP.ChainIDs, p.ChainIDs) copy(copyP.ChainIDs, p.ChainIDs)
copyP.Nonce = newNonce() copyP.Nonce = newNonce(nonceLength)
return copyP return copyP
} }
@ -71,22 +69,15 @@ func (pk *publicKeyAuthentication) GetPublicKeyRegistrationParams() map[string]i
return params return params
} }
var regexpNotAlphaDigit = regexp.MustCompile("[^a-zA-Z0-9]+") const lettersAndNumbers = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func newNonce() string { func newNonce(n int) string {
nonce := "" nonce := make([]byte, n)
rand.Seed(time.Now().UnixNano())
for len(nonce) < minNonceCharacterLength { for i := range nonce {
b := make([]byte, nonceByteLength) nonce[i] = lettersAndNumbers[rand.Int63()%int64(len(lettersAndNumbers))]
if _, err := rand.Read(b); err != nil {
return ""
}
// url-safe no padding
nonce = base64.RawURLEncoding.EncodeToString(b)
// Remove any non alphanumeric or digit to comply with spec EIP-4361
// nonce grammar.
nonce = regexpNotAlphaDigit.ReplaceAllString(nonce, "")
} }
return nonce return string(nonce)
} }