Search code examples
pythonparsingpem

Parsing PEM file into Object


I have a PEM file which contains some certificates. I want to parse them into an object which has a sha_hash, pem and expiration variables.

I have created the object and it works. I created a list of objects. The issue I am having is with Parsing. Please see the full code below. The issue is lets say I hit the SHA or BEGIN or END case.. it adds the line to the object.. but then it hits the else case.. and adds it a second time.

What I want to to do once it finishes one of the if statements is to go to the next line!

class Certificate(object):
    """A class for parsing and storing information about
    certificates:"""

    def __init__(self, sha_hash="", pem="", expiration=""):
        super(Certificate, self).__init__()
        self.sha_hash = sha_hash
        self.pem = pem
        self.expiration = expiration


def main():
    cert_file = '/Users/ludeth/Desktop/testCerts.pem'
    myList = []
    cert = Certificate()

    with open(cert_file, 'r') as myFile:
        cert = Certificate()
        for line in myFile:
            if "SHA" in line:
                cert.sha_hash = line
            if "BEGIN" in line:
                cert.pem = cert.pem + line
            if "END" in line:
                cert.pem = cert.pem + line
                myList.append(cert)
                break
            else:
                cert.pem = cert.pem + line

if __name__ == '__main__':
    main()

Solution

  • It's happens because you have multiple ifs and a if/else at the end. If you want to always match exactly one of these conditionals you could instead do

    if "SHA" in line:
        cert.sha_hash = line
    elif "BEGIN" in line:
        cert.pem = cert.pem + line
    elif "END" in line:
        cert.pem = cert.pem + line
        myList.append(cert)
        break
    else:
        cert.pem = cert.pem + line