Verify if a private key needs a passphrase or not

67 Views Asked by At

I want to write a piece of code which will load a certificate and its key and use them to set up HTTPS. I encountered the problem of an RSA key which requires a passphrase: if the key requires a passphrase and I don't pass it to the password argument of ssl.load_certs_chain, the code will hang waiting for user to prompt the passphrase.

What I would like to do instead is to either fail when the code tries to load the key or detect from the key if it needs a passphrase or not.

I tried to put a default value "-" to password paramter of ssl.load_cert_chain in order to get an error of "wrong password" if the key required a passphrase, but I only get this output

ssl.SSLError: [SSL] PEM lib (_ssl.c:4065)

which is meaningless. There is no details about the exception

1

There are 1 best solutions below

3
On

From the docs you linked:

The password argument may be a function to call to get the password for decrypting the private key. It will only be called if the private key is encrypted and a password is necessary. It will be called with no arguments, and it should return a string, bytes, or bytearray. If the return value is a string it will be encoded as UTF-8 before using it to decrypt the key. Alternatively a string, bytes, or bytearray value may be supplied directly as the password argument. It will be ignored if the private key is not encrypted and no password is needed.

If the password argument is not specified and a password is required, OpenSSL’s built-in password prompting mechanism will be used to interactively prompt the user for a password.

You could pass a function of your own that raises a custom exception if the password fails.