1#
2# This file is part of pyasn1-modules software.
3#
4# Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5# License: http://snmplabs.com/pyasn1/license.html
6#
7import base64
8
9stSpam, stHam, stDump = 0, 1, 2
10
11
12# The markers parameters is in form ('start1', 'stop1'), ('start2', 'stop2')...
13# Return is (marker-index, substrate)
14def readPemBlocksFromFile(fileObj, *markers):
15 startMarkers = dict(map(lambda x: (x[1], x[0]),
16 enumerate(map(lambda y: y[0], markers))))
17 stopMarkers = dict(map(lambda x: (x[1], x[0]),
18 enumerate(map(lambda y: y[1], markers))))
19 idx = -1
20 substrate = ''
21 certLines = []
22 state = stSpam
23 while True:
24 certLine = fileObj.readline()
25 if not certLine:
26 break
27 certLine = certLine.strip()
28 if state == stSpam:
29 if certLine in startMarkers:
30 certLines = []
31 idx = startMarkers[certLine]
32 state = stHam
33 continue
34 if state == stHam:
35 if certLine in stopMarkers and stopMarkers[certLine] == idx:
36 state = stDump
37 else:
38 certLines.append(certLine)
39 if state == stDump:
40 substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines])
41 break
42 return idx, substrate
43
44
45# Backward compatibility routine
46def readPemFromFile(fileObj,
47 startMarker='-----BEGIN CERTIFICATE-----',
48 endMarker='-----END CERTIFICATE-----'):
49 idx, substrate = readPemBlocksFromFile(fileObj, (startMarker, endMarker))
50 return substrate
51
52
53def readBase64fromText(text):
54 return base64.b64decode(text.encode())
55
56
57def readBase64FromFile(fileObj):
58 return readBase64fromText(fileObj.read())