From 14fad67d020c8401dff1fdc2484b99a3fc810594 Mon Sep 17 00:00:00 2001 From: Christian Rebischke Date: Fri, 26 Jun 2020 10:47:42 +0200 Subject: [PATCH] add test function for ParseRSAPrivateKey --- in_toto/keylib.go | 2 +- in_toto/keylib_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/in_toto/keylib.go b/in_toto/keylib.go index cc02e3e4..0f81aca8 100644 --- a/in_toto/keylib.go +++ b/in_toto/keylib.go @@ -57,7 +57,7 @@ func ParseRSAPrivateKeyFromPEM(pemBytes []byte) (*rsa.PrivateKey, error) { // Should we handle it / fail / say something about it? data, _ := pem.Decode(pemBytes) if data == nil { - return nil, fmt.Errorf("Could not find a Private key PEM block") + return nil, fmt.Errorf("Could not find a private key PEM block") } priv, err := x509.ParsePKCS1PrivateKey(data.Bytes) diff --git a/in_toto/keylib_test.go b/in_toto/keylib_test.go index 5efbc608..b45af7ae 100644 --- a/in_toto/keylib_test.go +++ b/in_toto/keylib_test.go @@ -57,6 +57,32 @@ yMxdI/24LUOOQ71cHW3ITIDImm6I8KmrXFM2NewTARKfAgMBAAE= } } +func TestParseRSAPrivateKeyFromPEM(t *testing.T) { + // Test parsing errors: + // - Missing pem headers, + // - Missing pem body + // We only support RSA private keys, therefore we don't need to check for other keys. + // Other keys should fail at ParsePKCS1 stage already. + invalidRSA := []string{ + "not a PEM block", + `-----BEGIN PRIVATE KEY----- + +-----END PRIVATE KEY-----`, + } + expectedErrors := []string{ + "Could not find a private key PEM block", + "truncated", + } + + for i := 0; i < len(invalidRSA); i++ { + result, err := ParseRSAPrivateKeyFromPEM([]byte(invalidRSA[i])) + if err == nil || !strings.Contains(err.Error(), expectedErrors[i]) { + t.Errorf("ParseRSAPrivateKeyFromPEM returned (%p, %s), expected '%s'"+ + " error", result, err, expectedErrors[i]) + } + } +} + func TestLoadRSAPublicKey(t *testing.T) { // Test loading valid public rsa key from pem-formatted file var key Key