Skip to content
This repository has been archived by the owner on Dec 7, 2019. It is now read-only.

Commit

Permalink
Merge pull request #43 from libp2p/fix/42
Browse files Browse the repository at this point in the history
forbid RSA keys smaller than 512 bits
  • Loading branch information
Stebalien authored Sep 28, 2018
2 parents 0f79fbe + 4b040bd commit 7240b40
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import (
sha256 "github.com/minio/sha256-simd"
)

// ErrRsaKeyTooSmall is returned when trying to generate or parse an RSA key
// that's smaller than 512 bits. Keys need to be larger enough to sign a 256bit
// hash so this is a reasonable absolute minimum.
var ErrRsaKeyTooSmall = errors.New("rsa keys must be >= 512 bits to be useful")

// RsaPrivateKey is an rsa private key
type RsaPrivateKey struct {
sk *rsa.PrivateKey
Expand All @@ -26,6 +31,9 @@ type RsaPublicKey struct {

// GenerateRSAKeyPair generates a new rsa private and public key
func GenerateRSAKeyPair(bits int, src io.Reader) (PrivKey, PubKey, error) {
if bits < 512 {
return nil, nil, ErrRsaKeyTooSmall
}
priv, err := rsa.GenerateKey(src, bits)
if err != nil {
return nil, nil, err
Expand Down Expand Up @@ -111,6 +119,9 @@ func UnmarshalRsaPrivateKey(b []byte) (PrivKey, error) {
if err != nil {
return nil, err
}
if sk.N.BitLen() < 512 {
return nil, ErrRsaKeyTooSmall
}
return &RsaPrivateKey{sk: sk}, nil
}

Expand All @@ -129,6 +140,9 @@ func UnmarshalRsaPublicKey(b []byte) (PubKey, error) {
if !ok {
return nil, errors.New("not actually an rsa public key")
}
if pk.N.BitLen() < 512 {
return nil, ErrRsaKeyTooSmall
}
return &RsaPublicKey{pk}, nil
}

Expand Down
7 changes: 7 additions & 0 deletions rsa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ func TestRSABasicSignAndVerify(t *testing.T) {
}
}

func TestRSASmallKey(t *testing.T) {
_, _, err := GenerateRSAKeyPair(384, rand.Reader)
if err != ErrRsaKeyTooSmall {
t.Fatal("should have refused to create small RSA key")
}
}

func TestRSASignZero(t *testing.T) {
priv, pub, err := GenerateRSAKeyPair(512, rand.Reader)
if err != nil {
Expand Down

0 comments on commit 7240b40

Please sign in to comment.