|
|
handlers = (
lambda c, p: (serialization.load_der_private_key(c, p), False),
lambda c, p: (serialization.load_pem_private_key(c, p), False),
lambda c, _: (serialization.load_der_public_key(c), True),
lambda c, _: (serialization.load_pem_public_key(c), True),
)
for key in self:
key.pem_key = None
key.public = None
key.loading_error = ""
content = key.with_context(bin_size=False).content
if not content:
continue
content = base64.b64decode(content)
pwd = key.password.encode('utf-8') if key.password else None
loading_error = self.env._("This key could not be loaded. Either its content or its password is erroneous.")
for handler in handlers:
try:
pkey, key.public = handler(content, pwd)
break
except TypeError:
# Raises TypeError if a password was given and the private key was not encrypted.
# Or if the key was encrypted but no password was supplied.
# We don't want to show an error if the user hasn't provided a password for an encrypted key yet.
if not pwd:
loading_error = ""
except ValueError:
pass
else:
key.loading_error = loading_error
continue
if key.public:
key.pem_key = base64.b64encode(pkey.public_bytes(
encoding=Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
))
else:
encryption = serialization.BestAvailableEncryption(pwd) if pwd else serialization.NoEncryption()
key.pem_key = base64.b64encode(pkey.private_bytes(
encoding=Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=encryption,
))
|
|