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