from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.x509.oid import NameOID, ExtensionOID
import sys
def pem_to_csr(pem_file_path, csr_file_path):
try:
# Load the PEM certificate
with open(pem_file_path, "rb") as pem_file:
cert = x509.load_pem_x509_certificate(pem_file.read())
# Extract the subject from the certificate
subject = cert.subject
subject_name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, subject.get_attributes_for_oid(NameOID.ORGANIZATION_NAME)[0].value),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)[0].value),
x509.NameAttribute(NameOID.COUNTRY_NAME, subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)[0].value)
])
# Extract SANs and other extensions
extensions = []
for extension in cert.extensions:
if isinstance(extension.value, x509.SubjectAlternativeName):
extensions.append(x509.SubjectAlternativeName([general_name.value for general_name in extension.value.get_values_for_type(x509.DNSName)]))
elif isinstance(extension.value, x509.BasicConstraints):
extensions.append(x509.BasicConstraints(ca=extension.value.ca, path_length=extension.value.path_length))
elif isinstance(extension.value, x509.KeyUsage):
extensions.append(x509.KeyUsage(
digital_signature=extension.value.digital_signature,
content_commitment=extension.value.content_commitment,
key_encipherment=extension.value.key_encipherment,
data_encipherment=extension.value.data_encipherment,
key_agreement=extension.value.key_agreement,
cert_sign=extension.value.cert_sign,
crl_sign=extension.value.crl_sign,
encipher_only=extension.value.encipher_only,
decipher_only=extension.value.decipher_only
))
elif isinstance(extension.value, x509.ExtendedKeyUsage):
extensions.append(x509.ExtendedKeyUsage([usage.dotted_string for usage in extension.value.usages]))
# Extract the public key from the certificate
public_key = cert.public_key()
# Generate the CSR
csr = x509.CertificateSigningRequestBuilder().subject_name(subject_name).add_extensions(
extensions
).sign(private_key=public_key, algorithm=hashes.SHA256())
# Write the CSR to a file
with open(csr_file_path, "wb") as csr_file:
csr_file.write(csr.public_bytes(serialization.Encoding.PEM))
print(f"CSR file generated: {csr_file_path}")
except FileNotFoundError:
print(f"Error: The file '{pem_file_path}' was not found.")
except x509.InvalidCertificate:
print(f"Error: The file '{pem_file_path}' does not contain a valid certificate.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python pem_to_csr.py <PEM_FILE> <CSR_FILE>")
sys.exit(1)
pem_file = sys.argv[1]
csr_file = sys.argv[2]
pem_to_csr(pem_file, csr_file)
This script reads a PEM certificate, extracts the subject, SANs, and other extensions, and generates a CSR with the same information. It handles SANs and extensions like Key Usage and Extended Key Usage.