from cryptography import x509
from cryptography.hazmat.primitives import hashes
import sys
import os

def compute_tbs_hash(cert_path):
    """Computes the SHA-384 hash of the TBS (To Be Signed) section of a certificate."""
    certs_to_calc = []
    if not os.path.exists(cert_path):
        print("You didn't provide a valid path")
    if os.path.isdir(cert_path):
        for (path, _, files) in os.walk(cert_path):
            certs_to_calc.extend([os.path.join(path, x) for x in files])
    elif os.path.isfile(cert_path):
        certs_to_calc.append(cert_path)

    for cert_path in certs_to_calc:
        try:
            # Read certificate file
            with open(cert_path, "rb") as f:
                cert_data = f.read()
            
            # Load the certificate
            cert = x509.load_pem_x509_certificate(cert_data)  # Try PEM first
        except ValueError:
            # If PEM fails, try DER format
            cert = x509.load_der_x509_certificate(cert_data)

        # Extract the TBS (To Be Signed) portion
        tbs_bytes = cert.tbs_certificate_bytes

        # Compute SHA-384 hash (48-byte output)
        digest = hashes.Hash(hashes.SHA384())
        digest.update(tbs_bytes)
        tbs_hash = digest.finalize()

        # Print the hash in a readable format
        print(f"{cert_path} - {tbs_hash.hex().upper()}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 calc_tbs_hash.py <certificate.crt | path/to/multiple/crts>")
        sys.exit(1)

    cert_path = sys.argv[1]
    compute_tbs_hash(cert_path)