|
1 | 1 | from cryptography import x509 |
2 | 2 | from cryptography.hazmat.backends import default_backend |
| 3 | +from cryptography.exceptions import UnsupportedAlgorithm, InvalidSignature |
3 | 4 |
|
4 | 5 |
|
5 | 6 | def extract_serial_number_from_cert_string(cert_string): |
6 | | - certificate = x509.load_pem_x509_certificate(cert_string.encode(), default_backend()) |
7 | | - decimal_serial = certificate.serial_number |
8 | | - # Convert to hexadecimal |
9 | | - hex_serial = format(decimal_serial, 'X') |
10 | | - # Ensure an even number of digits for correct byte representation |
11 | | - if len(hex_serial) % 2 != 0: |
12 | | - hex_serial = '0' + hex_serial |
13 | | - # Insert colons between every 2 characters |
14 | | - colon_separated_serial = ":".join(hex_serial[i:i+2] for i in range(0, len(hex_serial), 2)) |
15 | | - return colon_separated_serial |
| 7 | + try: |
| 8 | + certificate = x509.load_pem_x509_certificate(cert_string.encode(), default_backend()) |
| 9 | + decimal_serial = certificate.serial_number |
| 10 | + |
| 11 | + # Convert to hexadecimal |
| 12 | + hex_serial = format(decimal_serial, 'X') |
| 13 | + |
| 14 | + # Ensure an even number of digits for correct byte representation |
| 15 | + if len(hex_serial) % 2 != 0: |
| 16 | + hex_serial = '0' + hex_serial |
| 17 | + |
| 18 | + # Insert colons between every 2 characters |
| 19 | + colon_separated_serial = ":".join(hex_serial[i:i+2] for i in range(0, len(hex_serial), 2)) |
| 20 | + return colon_separated_serial |
| 21 | + |
| 22 | + except (ValueError, UnsupportedAlgorithm, InvalidSignature) as e: |
| 23 | + # You can specify more exceptions as needed based on the specific errors you're encountering. |
| 24 | + raise ValueError("Provided certificate string is not parsable: " + str(e)) |
0 commit comments