pyca / cryptography

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.
https://cryptography.io
Other
6.4k stars 1.47k forks source link

Please enhance the error message when loading the wrong kind of PEM file #11175

Closed nogweii closed 3 days ago

nogweii commented 5 days ago

Here is my certificate in PEM format:

-----BEGIN CERTIFICATE-----
MIIBPjCB8aADAgECAhAWvwpINskqCKt6XepYaZxZMAUGAytlcDAQMQ4wDAYDVQQK
EwV0YWxvczAeFw0yNDA2MjcwNTEzMzRaFw0zNDA2MjUwNTEzMzRaMBAxDjAMBgNV
BAoTBXRhbG9zMCowBQYDK2VwAyEAx/qRBUSyc6tE6V2a9Jv7DEFdTK4eil2+VizD
sSSrEiOjYTBfMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcDAQYI
KwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUXJDDQiRcx7mmPUki
4jhBqjvDLt8wBQYDK2VwA0EAQM8KKSD5okD0ombcy+w7atzR1yJAztkgXZ5gb4ER
RTcOCzAelm1zxMOoC3Tv3Q6L96XeYXc2j0hhUrL5jkJRBQ==
-----END CERTIFICATE-----

I was in the mindset of "I loaded the private key, so now I need to load the public key" and reached for serialization.load_pem_public_key. That results in the following error:

ValueError: Unable to load PEM file. See https://cryptography.io/en/latest/faq/#why-can-t-i-import-my-pem-file for more details. MalformedFraming

I spent a while trying to investigate the characters are all base64, encoded correctly in utf-8, removing the extra newline, all sorts of things. As it turns out, I'm using the wrong function to load this, and should have been using x509.load_pem_x509_certificate instead.

Obvious in retrospect, but very confusing in the moment. The PEM file is valid! But the wrong kind for that function. Perhaps expanding the error message a bit more, adding (looking for PUBLIC KEY) or similar to the end might help point out the mistake the user is doing.