Skip to content

Instantly share code, notes, and snippets.

@Soham3-1415
Created June 17, 2022 16:08
Show Gist options
  • Save Soham3-1415/0ee61af933f132a84dcca6bf15665842 to your computer and use it in GitHub Desktop.
Save Soham3-1415/0ee61af933f132a84dcca6bf15665842 to your computer and use it in GitHub Desktop.
Extract PEM stuff from your file with this one easy script. Plug it into Unix find to extract all the PEM stuff from all the files.
#!/bin/python3
import sys,re,json
PEM = re.compile(b'(?P<whole>(?P<header>(?:-----)(?:(?:BEGIN) (?P<type>(?:[A-Z]+ )*(?:[A-Z]+)))(?:-----)(?:\n|\r|\r\n))(?P<inner_base64>(?:(?:(?:[0-9a-zA-Z\+\/]{4}){16})(?:\n|\r|\r\n))*(?:(?:(?:[A-Za-z0-9+\/]{4}){0,15})(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4}))(?:\n|\r|\r\n))(?P<footer>(?:-----)(?:(?:END) (?P=type))(?:-----)))')
if not sys.argv[1]:
sys.exit(1)
filename = sys.argv[1]
extracted = {}
with open(filename,'rb') as f:
for d in map(lambda m: m.groupdict(), PEM.finditer(f.read())):
key = d['type'].decode().lower().replace(' ','_')
val = d['whole'].decode()
if key not in extracted:
extracted[key] = set()
extracted[key].add(val)
for k in extracted.keys():
extracted[k] = list(extracted[k])
if len(extracted) == 0:
sys.exit(0)
results = {}
results['path'] = filename
results['extracted'] = extracted
print(json.dumps(results))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment