You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pem.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #
  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 readBase64fromText(text):
  51. if sys.version_info[0] <= 2:
  52. return base64.b64decode(text)
  53. else:
  54. return base64.b64decode(text.encode())
  55. def readBase64FromFile(fileObj):
  56. return readBase64fromText(fileObj.read())