Add Better Zero Key Checks (#9022)

* add better checks

* preston's review
This commit is contained in:
Nishant Das
2021-06-12 02:48:57 +08:00
committed by GitHub
parent 6981b16ecd
commit fb08014146
3 changed files with 21 additions and 10 deletions

View File

@@ -4,6 +4,7 @@
package blst
import (
"crypto/subtle"
"fmt"
"github.com/prysmaticlabs/prysm/shared/bls/common"
@@ -28,7 +29,7 @@ func RandKey() (common.SecretKey, error) {
}
// Defensive check, that we have not generated a secret key,
secKey := &bls12SecretKey{blst.KeyGen(ikm[:])}
if secKey.IsZero() {
if IsZero(secKey.Marshal()) {
return nil, common.ErrZeroKey
}
return secKey, nil
@@ -44,7 +45,7 @@ func SecretKeyFromBytes(privKey []byte) (common.SecretKey, error) {
return nil, common.ErrSecretUnmarshal
}
wrappedKey := &bls12SecretKey{p: secKey}
if wrappedKey.IsZero() {
if IsZero(privKey) {
return nil, common.ErrZeroKey
}
return wrappedKey, nil
@@ -56,9 +57,12 @@ func (s *bls12SecretKey) PublicKey() common.PublicKey {
}
// IsZero checks if the secret key is a zero key.
func (s *bls12SecretKey) IsZero() bool {
zeroKey := new(blst.SecretKey)
return s.p.Equals(zeroKey)
func IsZero(sKey []byte) bool {
b := byte(0)
for _, s := range sKey {
b |= s
}
return subtle.ConstantTimeByteEq(b, 0) == 1
}
// Sign a message using a secret key - in a beacon/validator client.
@@ -80,9 +84,5 @@ func (s *bls12SecretKey) Sign(msg []byte) common.Signature {
// Marshal a secret key into a LittleEndian byte slice.
func (s *bls12SecretKey) Marshal() []byte {
keyBytes := s.p.Serialize()
if len(keyBytes) < params.BeaconConfig().BLSSecretKeyLength {
emptyBytes := make([]byte, params.BeaconConfig().BLSSecretKeyLength-len(keyBytes))
keyBytes = append(emptyBytes, keyBytes...)
}
return keyBytes
}

View File

@@ -5,6 +5,7 @@ package blst_test
import (
"bytes"
"crypto/rand"
"errors"
"testing"
@@ -85,3 +86,14 @@ func TestSerialize(t *testing.T) {
_, err = blst.SecretKeyFromBytes(b)
assert.NoError(t, err)
}
func TestZeroKey(t *testing.T) {
// Is Zero
zKey := [32]byte{}
assert.Equal(t, true, blst.IsZero(zKey[:]))
// Is Not Zero
_, err := rand.Read(zKey[:])
assert.NoError(t, err)
assert.Equal(t, false, blst.IsZero(zKey[:]))
}

View File

@@ -10,7 +10,6 @@ type SecretKey interface {
PublicKey() PublicKey
Sign(msg []byte) Signature
Marshal() []byte
IsZero() bool
}
// PublicKey represents a BLS public key.