diff --git a/crypto.go b/crypto.go index a705cdde..558c18cf 100644 --- a/crypto.go +++ b/crypto.go @@ -72,6 +72,10 @@ func encodePrivateKey(key crypto.PrivateKey) ([]byte, error) { func decodePrivateKey(keyPEMBytes []byte) (crypto.Signer, error) { keyBlockDER, _ := pem.Decode(keyPEMBytes) + if keyBlockDER == nil { + return nil, fmt.Errorf("failed to decode PEM block containing private key") + } + if keyBlockDER.Type != "PRIVATE KEY" && !strings.HasSuffix(keyBlockDER.Type, " PRIVATE KEY") { return nil, fmt.Errorf("unknown PEM header %q", keyBlockDER.Type) } diff --git a/crypto_test.go b/crypto_test.go index 71336ef6..e78c85b7 100644 --- a/crypto_test.go +++ b/crypto_test.go @@ -44,6 +44,12 @@ func TestEncodeDecodeRSAPrivateKey(t *testing.T) { t.Error("error loading private key:", err) } + // test load (should fail) + _, err = decodePrivateKey(savedBytes[2:]) + if err == nil { + t.Error("loading private key should have failed") + } + // verify loaded key is correct if !privateKeysSame(privateKey, loadedKey) { t.Error("Expected key bytes to be the same, but they weren't")