1import base64, sys
2
3stSpam, stHam, stDump = 0, 1, 2
4
5# The markers parameters is in form ('start1', 'stop1'), ('start2', 'stop2')...
6# Return is (marker-index, substrate)
7def readPemBlocksFromFile(fileObj, *markers):
8    startMarkers = dict(map(lambda x: (x[1],x[0]),
9                            enumerate(map(lambda x: x[0], markers))))
10    stopMarkers = dict(map(lambda x: (x[1],x[0]),
11                           enumerate(map(lambda x: x[1], markers))))
12    idx = -1; substrate = ''
13    state = stSpam
14    while 1:
15        certLine = fileObj.readline()
16        if not certLine:
17            break
18        certLine = certLine.strip()
19        if state == stSpam:
20            if certLine in startMarkers:
21                certLines = []
22                idx = startMarkers[certLine]
23                state = stHam
24                continue
25        if state == stHam:
26            if certLine in stopMarkers and stopMarkers[certLine] == idx:
27                state = stDump
28            else:
29                certLines.append(certLine)
30        if state == stDump:
31            if sys.version_info[0] <= 2:
32                substrate = ''.join([ base64.b64decode(x) for x in certLines ])
33            else:
34                substrate = ''.encode().join([ base64.b64decode(x.encode()) for x in certLines ])
35            break
36    return idx, substrate
37
38# Backward compatibility routine
39def readPemFromFile(fileObj,
40                    startMarker='-----BEGIN CERTIFICATE-----',
41                    endMarker='-----END CERTIFICATE-----'):
42    idx, substrate = readPemBlocksFromFile(fileObj, (startMarker, endMarker))
43    return substrate
44
45def readBase64FromFile(fileObj):
46    if sys.version_info[0] <= 2:
47        return ''.join([ base64.b64decode(x) for x in fileObj.readlines() ])
48    else:
49        return ''.encode().join(
50            [ base64.b64decode(x.encode()) for x in fileObj.readlines() ]
51        )
52