Skip to content

Commit

Permalink
secp256k1: Require concerete rand for privkey gen.
Browse files Browse the repository at this point in the history
This modifies the recently added GeneratePrivateKeyFromRand function to
require a concrete reader for the rand parameter instead of accepting
nil and defaulting to crypto/rand.Reader.

The primary motivation is to remove the otherwise unnecessary branch in
the private key generation.

The caller can easily pass in crypto/rand.Reader if desired, or even
better, just use GeneratePrivateKey instead since it already does
exactly that.  In other words, accepting nil doesn't provide any
additional functionality that isn't already easily accomplished and it
comes at the expense of an otherwise unnecessary branch.
  • Loading branch information
davecgh committed Apr 13, 2023
1 parent b4fab9e commit bd0b82d
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions dcrec/secp256k1/privkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ func PrivKeyFromBytes(privKeyBytes []byte) *PrivateKey {
return &privKey
}

// generatePrivateKey is a helper function for GeneratePrivateKey and
// GeneratePrivateKeyFromRand.
// generatePrivateKey generates and returns a new private key that is suitable
// for use with secp256k1 using the provided reader as a source of entropy. The
// provided reader must be a source of cryptographically secure randomness to
// avoid weak private keys.
func generatePrivateKey(rand io.Reader) (*PrivateKey, error) {
// The group order is close enough to 2^256 that there is only roughly a 1
// in 2^128 chance of generating an invalid private key, so this loop will
Expand Down Expand Up @@ -69,13 +71,11 @@ func GeneratePrivateKey() (*PrivateKey, error) {
return generatePrivateKey(cryptorand.Reader)
}

// GeneratePrivateKeyFromRand generates a private key using entropy from rand.
// If rand is nil, [crypto/rand.Reader] will be used.
// GeneratePrivateKeyFromRand generates a private key that is suitable for use
// with secp256k1 using the provided reader as a source of entropy. The
// provided reader must be a source of cryptographically secure randomness, such
// as [crypto/rand.Reader], to avoid weak private keys.
func GeneratePrivateKeyFromRand(rand io.Reader) (*PrivateKey, error) {
if rand == nil {
rand = cryptorand.Reader
}

return generatePrivateKey(rand)
}

Expand Down

0 comments on commit bd0b82d

Please sign in to comment.