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

Commit

Permalink
forbid RSA keys smaller than 512 bits
Browse files Browse the repository at this point in the history
We do use small keys for testing but keys smaller than this are entirely useless
as we need to be able to sign 256bit hashes.

fixes #42
  • Loading branch information
Stebalien committed Sep 28, 2018
1 parent 0f79fbe commit 4b040bd
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 4b040bd

Please # to comment.