Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Created November 5, 2020 09:27
Show Gist options
  • Save mzpqnxow/6b23dfd92f17acef62f10bfb04531c5d to your computer and use it in GitHub Desktop.
Save mzpqnxow/6b23dfd92f17acef62f10bfb04531c5d to your computer and use it in GitHub Desktop.
Crack a distinguished name string in Python
def crackdn(dn_str):
"""Crack a DN string into a dict
'C=US, ST=New Jersey, L=Newark, O=The Dump, Inc., CN=www.thedump.newark'
... Becomes ...
{
"C": "US",
"ST": "New Jersey",
"L": "Newark",
"O": "The Dump, Inc.",
"CN": "www.thedump.newark"
}
This is much, much simpler and cleaner if you don't need to handle components
that have commass- e.g. if "The Dump, Inc" was "The Dump Inc." this could
be done with an easily readable one-liner. Extra logic is required to account
for commas that may be inside fields
"""
if not dn_str:
return None
# This logic is required to normalize the DN string because
# we aren't given quoted or escaped values so they may contain
# commas that will break the basic cracking logic
# There is probably a cleaner way to do this but this is
# clear and works reliably
dn_list = []
for elt in dn_str.split(','):
if '=' in elt:
dn_list.append(elt)
continue
assert dn_list
dn_list.append(','.join([dn_list.pop(), elt]))
# The simple part
return dict([kvstr.strip().split('=') for kvstr in dn_list])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment