
    g                     p    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      Zy)z:SSL Certificate class for handling certificate operations.    N)DictAnyOptional)urlparse)Pathc            	       B   e Zd ZdZdeeef   fdZeddede	de
d    fd       Zededefd	       Zdde
e   de
e   fdZdde
e   de
e   fdZdde
e   de
e   fdZedeeef   fd       Zedeeef   fd       Zedefd       Zedefd       Zedefd       Zy
)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                 0    | j                  |      | _        y N)_decode_cert_data
_cert_info)selfr
   s     M/var/www/openai/venv/lib/python3.12/site-packages/crawl4ai/ssl_certificate.py__init__zSSLCertificate.__init__   s    00;    urltimeoutreturnc                    	 t        |       j                  }d|v r|j                  d      d   }t        j                         }t        j                  |df|      5 }|j                  ||      5 }|j                  d      }t        j                  j                  t        j                  j                  |      }t        |j                         j                               t        |j!                         j                               |j#                         t%        |j'                               |j)                         |j+                         |j-                  d      j%                         |j/                         t1        j2                  |      d		}g }	t5        |j7                               D ]>  }
|j9                  |
      }|	j;                  |j=                         t?        |      d
       @ |	|d<   tA        |      cddd       cddd       S # 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w# tB        $ r
}Y d}~yd}~ww xY 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es                r   from_urlzSSLCertificate.from_url    s   $	}++Hh#>>#.q1002G))8S/7Kt((x(HE"'"3"3"3"EK">>::7>>;W;WYdeD $((8(8(:(I(I(K#L"&t'8'G'G'I"J#'#3#3#5),T-C-C-E)F&*&8&8&:%)%6%6%8'+{{8'<'@'@'B/3/K/K/M$*$4$4[$A
!I "$J"4#;#;#=>"003"))$'$6$6$8%(X+  ? /9Il+))45 IH LKHHH LKK:  		sO   AH0 H$0FH;	H$	H0 H	H$H0 $H-)H0 -H0 0	I>Idatac                    t        | t              r| j                  d      S t        | t              rX| j	                         D ci c]<  \  }}t        |t              r|j                  d      n|t
        j                  |      > c}}S t        | t              r#| D cg c]  }t
        j                  |       c}S | S c c}}w c c}w )z2Helper method to decode bytes in certificate data.utf-8)
isinstancebytesdecoder3   itemsr	   r   list)rQ   kvitems       r   r   z SSLCertificate._decode_cert_dataR   s     dE";;w''d# !JJL(DAq '1E&:'"NDdDdefDgg(  d#GKLttN44T:tLL
 Ms   AB?CNfilepathc                     t        j                  | j                  dd      }|rt        |      j	                  |d       y|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_asciirS   encodingN)jsondumpsr   r   
write_text)r   r\   json_strs      r   to_jsonzSSLCertificate.to_json`   s<     ::dooaeLN%%h%Ar   c                    	 t         j                  j                  t         j                  j                  t	        j
                  | j                  d               }t         j                  j                  t         j                  j                  |      j                  d      }|rt        |      j                  |d       y|S # t        $ r
}Y d}~yd}~ww xY 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#   rS   ra   N)r/   r0   r1   r2   r>   	b64decoder   dump_certificateFILETYPE_PEMrV   r   re   rF   )r   r\   rL   pem_datarO   s        r   to_pemzSSLCertificate.to_pemp   s    	>>22,,  !<=D ~~66++ fWo 
 X))(W)EO 		s   B=C  C 	CCc                     	 t        j                  | j                  d         }|rt        |      j	                  |       y|S # t
        $ r Y yw xY 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>   ri   r   r   write_bytesrF   )r   r\   der_datas      r   to_derzSSLCertificate.to_der   sO    	''
(CDHX**84O 		s   >A A 	AAc                 :    | j                   j                  di       S )z#Get certificate issuer information.r   r   getr   s    r   r   zSSLCertificate.issuer   s     ""8R00r   c                 :    | j                   j                  di       S )z$Get certificate subject information.r   rs   ru   s    r   r   zSSLCertificate.subject   s     ""9b11r   c                 :    | j                   j                  dd      S )z$Get certificate validity start date.r    rs   ru   s    r   
valid_fromzSSLCertificate.valid_from   s     ""<44r   c                 :    | j                   j                  dd      S )z"Get certificate validity end date.r    rx   rs   ru   s    r   valid_untilzSSLCertificate.valid_until   s     "";33r   c                 :    | j                   j                  dd      S )zGet certificate fingerprint.r!   rx   rs   ru   s    r   r!   zSSLCertificate.fingerprint   s     ""="55r   )
   r   )__name__
__module____qualname____doc__r   rE   r   r   staticmethodintr   rP   r   rg   rm   rU   rq   propertyr   r   ry   r{   r!    r   r   r	   r	      sU   <$sCx. < /c /C /:J1K / /b     #  x}  6x}  & 1S#X 1 1 2c3h 2 2 5C 5 5 4S 4 4 6S 6 6r   r	   )r   r)   r+   r>   rc   typingr   r   r   urllib.parser   OpenSSL.cryptor/   pathlibr   r	   r   r   r   <module>r      s/    @ 
    & & !  h6 h6r   