|
| 1 | +import base64 |
| 2 | +from hashlib import sha1 |
| 3 | +from textwrap import wrap |
| 4 | + |
| 5 | + |
| 6 | +def format_finger_print(fingerprint): |
| 7 | + """ |
| 8 | + Formates a fingerprint. |
| 9 | +
|
| 10 | + :param fingerprint: fingerprint |
| 11 | + :type: string |
| 12 | +
|
| 13 | + :returns: Formated fingerprint |
| 14 | + :rtype: string |
| 15 | + """ |
| 16 | + formated_fingerprint = fingerprint.replace(':', '') |
| 17 | + return formated_fingerprint.lower() |
| 18 | + |
| 19 | + |
| 20 | +def calculate_x509_fingerprint(x509_cert): |
| 21 | + """ |
| 22 | + Calculates the fingerprint of a x509cert. |
| 23 | +
|
| 24 | + :param x509_cert: x509 cert |
| 25 | + :type: string |
| 26 | +
|
| 27 | + :returns: Formated fingerprint |
| 28 | + :rtype: string |
| 29 | + """ |
| 30 | + assert isinstance(x509_cert, basestring) |
| 31 | + |
| 32 | + lines = x509_cert.split('\n') |
| 33 | + data = '' |
| 34 | + |
| 35 | + for line in lines: |
| 36 | + # Remove '\r' from end of line if present. |
| 37 | + line = line.rstrip() |
| 38 | + if line == '-----BEGIN CERTIFICATE-----': |
| 39 | + # Delete junk from before the certificate. |
| 40 | + data = '' |
| 41 | + elif line == '-----END CERTIFICATE-----': |
| 42 | + # Ignore data after the certificate. |
| 43 | + break |
| 44 | + elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----': |
| 45 | + # This isn't an X509 certificate. |
| 46 | + return None |
| 47 | + else: |
| 48 | + # Append the current line to the certificate data. |
| 49 | + data += line |
| 50 | + # "data" now contains the certificate as a base64-encoded string. The |
| 51 | + # fingerprint of the certificate is the sha1-hash of the certificate. |
| 52 | + return sha1(base64.b64decode(data)).hexdigest().lower() |
| 53 | + |
| 54 | + |
| 55 | +def format_cert(cert, heads=True): |
| 56 | + """ |
| 57 | + Returns a x509 cert (adding header & footer if required). |
| 58 | +
|
| 59 | + :param cert: A x509 unformated cert |
| 60 | + :type: string |
| 61 | +
|
| 62 | + :param heads: True if we want to include head and footer |
| 63 | + :type: boolean |
| 64 | +
|
| 65 | + :returns: Formated cert |
| 66 | + :rtype: string |
| 67 | + """ |
| 68 | + x509_cert = cert.replace('\x0D', '') |
| 69 | + x509_cert = x509_cert.replace('\r', '') |
| 70 | + x509_cert = x509_cert.replace('\n', '') |
| 71 | + if len(x509_cert) > 0: |
| 72 | + x509_cert = x509_cert.replace('-----BEGIN CERTIFICATE-----', '') |
| 73 | + x509_cert = x509_cert.replace('-----END CERTIFICATE-----', '') |
| 74 | + x509_cert = x509_cert.replace(' ', '') |
| 75 | + |
| 76 | + if heads: |
| 77 | + x509_cert = '-----BEGIN CERTIFICATE-----\n' + '\n'.join(wrap(x509_cert, 64)) + '\n-----END CERTIFICATE-----\n' |
| 78 | + |
| 79 | + return x509_cert |
0 commit comments