a
    ~Pg	                     @   sh   d dl Z d dlZd dlmZ d dlmZmZ d dlmZ d dl	m
Z
mZmZ dd Zdd	 Zd
d ZdS )    N)InvalidSignature)ecutils)hashes)b64urldecodeb64urlencodenum_to_bytesc                 C   sn   |  ddd\}}t|}t|dkr0t tjtt	|dd dtt	|dd dd}||fS )	zExtracts the payload and signature from a JWT, converting from RFC7518
    to RFC 3279

    :param auth: A JWT Authorization Token.
    :type auth: str

    :return tuple containing the signature material and signature

    utf8   .   @       N   )sr)
encodersplitr   lenr   r   Zencode_dss_signatureintbinasciihexlify)authpayloadZasigsigencoded r   Z/var/www/staging/api/virtual_environments/venv/lib/python3.9/site-packages/py_vapid/jwt.pyextract_signature   s    
r   c              
   C   s   zdt | \}}t|d}tjt |}|||tt	
  tt|dd dW S  tyx    Y n  tttjfy   t Y n0 dS )zDecode a web token into an assertion dictionary

    :param token: VAPID auth token
    :type token: str
    :param key: bitarray containing the public key
    :type key: str

    :return dict of the VAPID claims

    :raise InvalidSignature

    r	   r
   r   N)r   r   r   r   ZEllipticCurvePublicKeyZfrom_encoded_pointZ	SECP256R1verifyECDSAr   SHA256jsonloadssplitdecoder   
ValueError	TypeErrorr   Error)tokenkeyZsig_material	signatureZdkeypkeyr   r   r   r$   !   s&    r$   c                 C   s|   t d}t tj| dddd} d|| }||dtt	 }t
|\}}t t|dt|d }d||S )zSign the claims

    :param claims: list of JWS claims
    :type claims: dict
    :param key: Private key for signing
    :type key: ec.EllipticCurvePrivateKey
    :param algorithm: JWT "alg" descriptor
    :type algorithm: str

    s   {"typ":"JWT","alg":"ES256"}),:T)
separators	sort_keysr	   z{}.{}r   )r   r!   dumpsr   formatsignr   r   r   r    r   Zdecode_dss_signaturer   )Zclaimsr)   headerr(   Zrsigr   r   r   r   r   r   r2   C   s    r2   )r   r!   Zcryptography.exceptionsr   Z)cryptography.hazmat.primitives.asymmetricr   r   Zcryptography.hazmat.primitivesr   Zpy_vapid.utilsr   r   r   r   r$   r2   r   r   r   r   <module>   s   "