pem.py 1.8 KB

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