o
    h                     @   sj   d Z ddlZddlZddlZddlZddlmZmZmZ ddl	m
Z
 ddlZddlmZ G dd dZdS )z:SSL Certificate class for handling certificate operations.    N)DictAnyOptional)urlparse)Pathc                	   @   s  e Zd ZdZdeeef fddZed dede	de
d  fd	d
ZededefddZd!de
e de
e fddZd!de
e de
e fddZd!de
e de
e fddZedeeef fddZedeeef fddZedefddZedefddZedefddZdS )"SSLCertificatean  
    A class representing an SSL certificate with methods to export in various formats.
    
    Attributes:
        cert_info (Dict[str, Any]): The certificate information.
        
        Methods:
            from_url(url: str, timeout: int = 10) -> Optional['SSLCertificate']: Create SSLCertificate instance from a URL.
            from_file(file_path: str) -> Optional['SSLCertificate']: Create SSLCertificate instance from a file.
            from_binary(binary_data: bytes) -> Optional['SSLCertificate']: Create SSLCertificate instance from binary data.
            export_as_pem() -> str: Export the certificate as PEM format.
            export_as_der() -> bytes: Export the certificate as DER format.
            export_as_json() -> Dict[str, Any]: Export the certificate as JSON format.
            export_as_text() -> str: Export the certificate as text format.
    	cert_infoc                 C   s   |  || _d S N)_decode_cert_data
_cert_info)selfr    r   U/var/www/Befach/backend/venv/lib/python3.10/site-packages/crawl4ai/ssl_certificate.py__init__   s   zSSLCertificate.__init__
   urltimeoutreturnc                 C   s  zt | j}d|v r|dd }t }tj|df|d}|j||do}|jdd}t	j
t	j
j|}t|  t|  | t| | | |d | t|d		}g }	t| D ]}
||
}|	| t|d
 qj|	|d< t |W  d   W  d   W S 1 sw   Y  W d   W dS 1 sw   Y  W dS  t!y } zW Y d}~dS d}~ww )a:  
        Create SSLCertificate instance from a URL.
        
        Args:
            url (str): URL of the website.
            timeout (int): Timeout for the connection (default: 10).
        
        Returns:
            Optional[SSLCertificate]: SSLCertificate instance if successful, None otherwise.
        :r   i  )r   )server_hostnameT)binary_formsha256)	subjectissuerversionserial_number
not_before	not_afterfingerprintsignature_algorithmraw_cert)namevalue
extensionsN)"r   netlocsplitsslcreate_default_contextsocketcreate_connectionwrap_socketgetpeercertOpenSSLcryptoload_certificateFILETYPE_ASN1dictget_subjectget_components
get_issuerget_versionhexget_serial_numberget_notBeforeget_notAfterdigestget_signature_algorithmbase64	b64encoderangeget_extension_countget_extensionappendget_short_namestrr   	Exception)r   r   hostnamecontextsockssockcert_binaryx509r   r#   iexter   r   r   from_url    sH   



&zSSLCertificate.from_urldatac                 C   sL   t | tr
| dS t | trdd |  D S t | tr$dd | D S | S )z2Helper method to decode bytes in certificate data.utf-8c                 S   s0   i | ]\}}t |tr|d n|t|qS )rO   )
isinstancebytesdecoder   r
   ).0kvr   r   r   
<dictcomp>X   s    z4SSLCertificate._decode_cert_data.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r   )r   r
   )rS   itemr   r   r   
<listcomp>]   s    z4SSLCertificate._decode_cert_data.<locals>.<listcomp>)rP   rQ   rR   r0   itemslist)rN   r   r   r   r
   R   s   



z SSLCertificate._decode_cert_dataNfilepathc                 C   s0   t j| jddd}|rt|j|dd dS |S )z
        Export certificate as JSON.
        
        Args:
            filepath (Optional[str]): Path to save the JSON file (default: None).
        
        Returns:
            Optional[str]: JSON string if successful, None otherwise.
           F)indentensure_asciirO   encodingN)jsondumpsr   r   
write_text)r   r[   json_strr   r   r   to_json`   s
   
zSSLCertificate.to_jsonc              
   C   s   z,t jt jjt| jd }t jt jj|	d}|r*t
|j|dd W dS |W S  ty? } zW Y d}~dS d}~ww )z
        Export certificate as PEM.
        
        Args:
            filepath (Optional[str]): Path to save the PEM file (default: None).
        
        Returns:
            Optional[str]: PEM string if successful, None otherwise.
        r    rO   r_   N)r,   r-   r.   r/   r;   	b64decoder   dump_certificateFILETYPE_PEMrR   r   rc   rC   )r   r[   rI   pem_datarL   r   r   r   to_pemp   s&   
zSSLCertificate.to_pemc                 C   sD   zt | jd }|rt|| W dS |W S  ty!   Y dS w )z
        Export certificate as DER.
        
        Args:
            filepath (Optional[str]): Path to save the DER file (default: None).
        
        Returns:
            Optional[bytes]: DER bytes if successful, None otherwise.
        r    N)r;   rf   r   r   write_bytesrC   )r   r[   der_datar   r   r   to_der   s   
zSSLCertificate.to_derc                 C      | j di S )z#Get certificate issuer information.r   r   getr   r   r   r   r         zSSLCertificate.issuerc                 C   rn   )z$Get certificate subject information.r   ro   rq   r   r   r   r      rr   zSSLCertificate.subjectc                 C      | j ddS )z$Get certificate validity start date.r    ro   rq   r   r   r   
valid_from   rr   zSSLCertificate.valid_fromc                 C   rs   )z"Get certificate validity end date.r   rt   ro   rq   r   r   r   valid_until   rr   zSSLCertificate.valid_untilc                 C   rs   )zGet certificate fingerprint.r   rt   ro   rq   r   r   r   r      rr   zSSLCertificate.fingerprint)r   r	   )__name__
__module____qualname____doc__r   rB   r   r   staticmethodintr   rM   r
   re   rj   rQ   rm   propertyr   r   ru   rv   r   r   r   r   r   r      s(    1r   )rz   r&   r(   r;   ra   typingr   r   r   urllib.parser   OpenSSL.cryptor,   pathlibr   r   r   r   r   r   <module>   s    