codekingpro/portable-devtools
114k
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.html6#7import base648 9stSpam, stHam, stDump = 0, 1, 210 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 = -120 substrate = ''21 certLines = []22 state = stSpam23 while True:24 certLine = fileObj.readline()25 if not certLine:26 break27 certLine = certLine.strip()28 if state == stSpam:29 if certLine in startMarkers:30 certLines = []31 idx = startMarkers[certLine]32 state = stHam33 continue34 if state == stHam:35 if certLine in stopMarkers and stopMarkers[certLine] == idx:36 state = stDump37 else:38 certLines.append(certLine)39 if state == stDump:40 substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines])41 break42 return idx, substrate43 44 45# Backward compatibility routine46def readPemFromFile(fileObj,47 startMarker='-----BEGIN CERTIFICATE-----',48 endMarker='-----END CERTIFICATE-----'):49 idx, substrate = readPemBlocksFromFile(fileObj, (startMarker, endMarker))50 return substrate51 52 53def readBase64fromText(text):54 return base64.b64decode(text.encode())55 56 57def readBase64FromFile(fileObj):58 return readBase64fromText(fileObj.read())59 