def load_private_key(secret, pass_phrase):
"""Loads a private key that may use a pass_phrase.
Tries to correct or diagnose common errors:
- provided pass_phrase but didn't need one
- provided a public key
"""
if isinstance(secret, six.text_type):
secret = secret.encode("ascii")
if isinstance(pass_phrase, six.text_type):
pass_phrase = pass_phrase.encode("ascii")
backend = default_backend()
try:
# 0) Try with pass_phrase
return serialization.load_pem_private_key(secret, pass_phrase, backend=backend)
except TypeError:
# 1) Either:
# - key has pass_phrase and one wasn't provided
# - key doesn't have pass_phrase and one was provided.
#
# Can't fix the first, but we *can* fix the second.
# This can happen if the DEFAULT profile has a pass_phrase but
# another profile uses a key file without a pass_phrase.
if pass_phrase is None:
# 1.1) private key needed a pass_phrase and we don't have one
raise MissingPrivateKeyPassphrase("The provided key requires a passphrase.")
else:
# 1.2) try again without pass_phrase; could be an artifact from DEFAULT
return serialization.load_pem_private_key(secret, None, backend=backend)
except ValueError:
# 2) Try to determine what kind of failure this is.
# Most likely, this is either a bad password or a public key.
# If loading it as a public key fails, it's almost certainly a bad password.
for loader in [
serialization.load_der_public_key,
serialization.load_pem_public_key,
serialization.load_ssh_public_key
]:
try:
loader(secret, backend=backend)
except (ValueError, UnsupportedAlgorithm):
# 2.1) Not a public key; try the next format
pass
else:
# 2.2) This is a public key
raise InvalidPrivateKey("Authentication requires a private key, but a public key was provided.")
# 2.3) Password is probably wrong.
raise InvalidPrivateKey("The provided key is not a private key, or the provided passphrase is incorrect.")
评论列表
文章目录