Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto/rsa: check RSA private/public key size before using it #66918

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/crypto/rsa/pkcs1v15.go
Expand Up @@ -292,6 +292,9 @@ func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed [

tLen := len(prefix) + hashLen
k := priv.Size()
if k == 0 {
return nil, errPrivateKeySizeZero
}
if k < tLen+11 {
return nil, ErrMessageTooLong
}
Expand Down
13 changes: 13 additions & 0 deletions src/crypto/rsa/pkcs1v15_test.go
Expand Up @@ -213,6 +213,19 @@ func TestSignPKCS1v15(t *testing.T) {
}
}

func TestSignPKCS1v15WithPrivateKeySizeZero(t *testing.T) {
h := sha1.New()
h.Write([]byte("key"))
digest := h.Sum(nil)
_, err := SignPKCS1v15(nil, &PrivateKey{}, crypto.SHA1, digest)
if err == nil {
t.Error("expected error but got nil")
}
if err != nil && err.Error() != "crypto/rsa: private key size zero" {
t.Errorf("unexpected error: %v", err)
}
}

func TestVerifyPKCS1v15(t *testing.T) {
for i, test := range signPKCS1v15Tests {
h := sha1.New()
Expand Down
5 changes: 5 additions & 0 deletions src/crypto/rsa/rsa.go
Expand Up @@ -89,6 +89,8 @@ var (
errPublicModulus = errors.New("crypto/rsa: missing public modulus")
errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small")
errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large")
errPublicKeySizeZero = errors.New("crypto/rsa: public key size zero")
errPrivateKeySizeZero = errors.New("crypto/rsa: private key size zero")
)

// checkPub sanity checks the public key before we use it.
Expand All @@ -106,6 +108,9 @@ func checkPub(pub *PublicKey) error {
if pub.E > 1<<31-1 {
return errPublicExponentLarge
}
if pub.Size() == 0 {
return errPublicKeySizeZero
}
return nil
}

Expand Down
11 changes: 11 additions & 0 deletions src/crypto/rsa/rsa_test.go
Expand Up @@ -654,6 +654,17 @@ func TestEncryptOAEP(t *testing.T) {
}
}

func TestEncryptOAEPWithPublicKeySizeZero(t *testing.T) {
sha1 := sha1.New()
_, err := EncryptOAEP(sha1, nil, &PublicKey{}, nil, nil)
if err == nil {
t.Error("expected error but got nil")
}
if err != nil && err.Error() != "crypto/rsa: public key size zero" {
t.Errorf("unexpected error: %v", err)
}
}

func TestDecryptOAEP(t *testing.T) {
random := rand.Reader

Expand Down