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