keys.py 1.38 KB
Newer Older
1
2
3
4
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend

5
6
import re
import urllib.parse
7
8


Eliot Berriot's avatar
Eliot Berriot committed
9
KEY_ID_REGEX = re.compile(r"keyId=\"(?P<id>.*)\"")
10

11
12
13

def get_key_pair(size=2048):
    key = rsa.generate_private_key(
Eliot Berriot's avatar
Eliot Berriot committed
14
        backend=crypto_default_backend(), public_exponent=65537, key_size=size
15
16
17
18
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
Eliot Berriot's avatar
Eliot Berriot committed
19
20
        crypto_serialization.NoEncryption(),
    )
21
    public_key = key.public_key().public_bytes(
Eliot Berriot's avatar
Eliot Berriot committed
22
        crypto_serialization.Encoding.PEM, crypto_serialization.PublicFormat.PKCS1
23
24
25
26
27
    )

    return private_key, public_key


28
def get_key_id_from_signature_header(header_string):
Eliot Berriot's avatar
Eliot Berriot committed
29
    parts = header_string.split(",")
30
    try:
31
32
        raw_key_id = [p for p in parts if p.startswith('keyId="')][0]
    except IndexError:
Eliot Berriot's avatar
Eliot Berriot committed
33
        raise ValueError("Missing key id")
34
35
36

    match = KEY_ID_REGEX.match(raw_key_id)
    if not match:
Eliot Berriot's avatar
Eliot Berriot committed
37
        raise ValueError("Invalid key id")
38
39
40
41

    key_id = match.groups()[0]
    url = urllib.parse.urlparse(key_id)
    if not url.scheme or not url.netloc:
Eliot Berriot's avatar
Eliot Berriot committed
42
43
44
        raise ValueError("Invalid url")
    if url.scheme not in ["http", "https"]:
        raise ValueError("Invalid shceme")
45
    return key_id