from aspen_crypto.keys import PublicKey
from django.core.exceptions import ValidationError


def validate_public_key(keystr: str) -> None:
    """
    Check that the given value is a valid public key in either PEM or OpenSSH format.
    If it is invalid, raises ``django.core.exceptions.ValidationError``.
    """
    # Encode to bytes, unicode_escape and back to bytes
    # to handle values that come from HTML form fields.
    key_bytes = keystr.encode().decode('unicode_escape').encode()
    exc, key = PublicKey.load_serialized_public_key(key_bytes)
    is_valid = (exc is None) and (key is not None)
    if not is_valid:
        raise ValidationError(f"Public key is invalid: {exc}")


__all__ = [
    'validate_public_key',
]
