diff --git a/tlsutil/generate.go b/tlsutil/generate.go index 5a3f0b4ed7..a402497a49 100644 --- a/tlsutil/generate.go +++ b/tlsutil/generate.go @@ -166,34 +166,7 @@ func parseCert(pemValue string) (*x509.Certificate, error) { // ParseSigner parses a crypto.Signer from a PEM-encoded key. The private key // is expected to be the first block in the PEM value. func ParseSigner(pemValue string) (crypto.Signer, error) { - // The _ result below is not an error but the remaining PEM bytes. - block, _ := pem.Decode([]byte(pemValue)) - if block == nil { - return nil, fmt.Errorf("no PEM-encoded data found") - } - - switch block.Type { - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(block.Bytes) - - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(block.Bytes) - - case "PRIVATE KEY": - signer, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - return nil, err - } - pk, ok := signer.(crypto.Signer) - if !ok { - return nil, fmt.Errorf("private key is not a valid format") - } - - return pk, nil - - default: - return nil, fmt.Errorf("unknown PEM block type for signing key: %s", block.Type) - } + return connect.ParseSigner(pemValue) } func Verify(caString, certString, dns string) error { diff --git a/tlsutil/generate_test.go b/tlsutil/generate_test.go index e8957ba2a8..5cceb727e1 100644 --- a/tlsutil/generate_test.go +++ b/tlsutil/generate_test.go @@ -95,6 +95,25 @@ func TestGenerateCA(t *testing.T) { require.WithinDuration(t, cert.NotAfter, time.Now().AddDate(0, 0, 365), time.Minute) require.Equal(t, x509.KeyUsageCertSign|x509.KeyUsageCRLSign|x509.KeyUsageDigitalSignature, cert.KeyUsage) + + // Test what happens with a correct RSA Key + s, err = rsa.GenerateKey(rand.Reader, 2048) + require.Nil(t, err) + ca, err = GenerateCA(s, sn, 365, nil) + require.Nil(t, err) + require.NotEmpty(t, ca) + + cert, err = parseCert(ca) + require.Nil(t, err) + require.Equal(t, fmt.Sprintf("Consul Agent CA %d", sn), cert.Subject.CommonName) + require.Equal(t, true, cert.IsCA) + require.Equal(t, true, cert.BasicConstraintsValid) + + require.WithinDuration(t, cert.NotBefore, time.Now(), time.Minute) + require.WithinDuration(t, cert.NotAfter, time.Now().AddDate(0, 0, 365), time.Minute) + + require.Equal(t, x509.KeyUsageCertSign|x509.KeyUsageCRLSign|x509.KeyUsageDigitalSignature, cert.KeyUsage) + } func TestGenerateCert(t *testing.T) {