Skip to content

Utility to detect a key type from a raw string #73

@azmeuk

Description

@azmeuk

It would be nice to have an utility that guess a key type from a raw string.

My use case is that I want to allow users to use their historical private keys in .key format, and let them time to switch to a JWK format.

Ideally, jwk.import_key could take a raw key in parameter.

It could be something like this:

from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import ed448
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import x448
from cryptography.hazmat.primitives.asymmetric import x25519
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from joserfc.jwk import ECKey
from joserfc.jwk import OKPKey
from joserfc.jwk import RSAKey


def detect_key_type(raw_key: str):
    try:
        private_key = serialization.load_pem_private_key(raw_key, password=None)
    except Exception:
        try:
            private_key = serialization.load_der_private_key(
                raw_key, password=None
            )
        except Exception:
            return None

    if isinstance(private_key, rsa.RSAPrivateKey):
        return RSAKey
    if isinstance(private_key, ec.EllipticCurvePrivateKey):
        return ECKey
    if isinstance(private_key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)):
        return OKPKey
    if isinstance(private_key, (x25519.X25519PrivateKey, x448.X448PrivateKey)):
        return OKPKey
    if isinstance(private_key, dsa.DSAPrivateKey):
        return None

    return None

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions