pem.py 2.0 KB

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