pem.py 1.8 KB

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