2018-03-31 13:47:21 +00:00
|
|
|
import re
|
|
|
|
import urllib.parse
|
2018-03-28 16:04:21 +00:00
|
|
|
|
2018-06-10 08:55:16 +00:00
|
|
|
from cryptography.hazmat.backends import default_backend as crypto_default_backend
|
|
|
|
from cryptography.hazmat.primitives import serialization as crypto_serialization
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
2018-03-28 16:04:21 +00:00
|
|
|
|
2018-06-09 13:36:16 +00:00
|
|
|
KEY_ID_REGEX = re.compile(r"keyId=\"(?P<id>.*)\"")
|
2018-03-31 13:47:21 +00:00
|
|
|
|
2018-03-28 16:04:21 +00:00
|
|
|
|
|
|
|
def get_key_pair(size=2048):
|
|
|
|
key = rsa.generate_private_key(
|
2018-06-09 13:36:16 +00:00
|
|
|
backend=crypto_default_backend(), public_exponent=65537, key_size=size
|
2018-03-28 16:04:21 +00:00
|
|
|
)
|
|
|
|
private_key = key.private_bytes(
|
|
|
|
crypto_serialization.Encoding.PEM,
|
|
|
|
crypto_serialization.PrivateFormat.PKCS8,
|
2018-06-09 13:36:16 +00:00
|
|
|
crypto_serialization.NoEncryption(),
|
|
|
|
)
|
2018-03-28 16:04:21 +00:00
|
|
|
public_key = key.public_key().public_bytes(
|
2018-06-09 13:36:16 +00:00
|
|
|
crypto_serialization.Encoding.PEM, crypto_serialization.PublicFormat.PKCS1
|
2018-03-28 16:04:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
return private_key, public_key
|
|
|
|
|
|
|
|
|
2018-03-31 13:47:21 +00:00
|
|
|
def get_key_id_from_signature_header(header_string):
|
2018-06-09 13:36:16 +00:00
|
|
|
parts = header_string.split(",")
|
2018-03-28 16:04:21 +00:00
|
|
|
try:
|
2018-03-31 13:47:21 +00:00
|
|
|
raw_key_id = [p for p in parts if p.startswith('keyId="')][0]
|
|
|
|
except IndexError:
|
2018-06-09 13:36:16 +00:00
|
|
|
raise ValueError("Missing key id")
|
2018-03-31 13:47:21 +00:00
|
|
|
|
|
|
|
match = KEY_ID_REGEX.match(raw_key_id)
|
|
|
|
if not match:
|
2018-06-09 13:36:16 +00:00
|
|
|
raise ValueError("Invalid key id")
|
2018-03-31 13:47:21 +00:00
|
|
|
|
|
|
|
key_id = match.groups()[0]
|
|
|
|
url = urllib.parse.urlparse(key_id)
|
|
|
|
if not url.scheme or not url.netloc:
|
2018-06-09 13:36:16 +00:00
|
|
|
raise ValueError("Invalid url")
|
|
|
|
if url.scheme not in ["http", "https"]:
|
|
|
|
raise ValueError("Invalid shceme")
|
2018-03-31 13:47:21 +00:00
|
|
|
return key_id
|