use M2Crypto instead of openssl command line/subprocess for CSR parsing

This commit is contained in:
Eric Wustrow
2012-07-12 18:07:13 -04:00
parent d54858689a
commit 19df04c516
+50 -19
View File
@@ -35,31 +35,62 @@ def csr_goodkey(csr):
return goodkey(key) return goodkey(key)
def pubkey(csr): def pubkey(csr):
"""Get the public key from this CSR.""" """
out, err = subprocess.Popen(["openssl", "req", "-pubkey", "-noout"],shell=False,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate(csr) Get the public key from this Certificate Signing Request.
if out and not err:
return out @type csr: string
return None @param csr: PEM-encoded string of the CSR.
@return: a string of the PEM-encoded public key
"""
req = M2Crypto.X509.load_request_string(csr)
return req.get_pubkey().as_pem(None)
def subject(csr): def subject(csr):
"""Get the X.509 subject from this CSR.""" """
out, err = subprocess.Popen(["openssl", "req", "-subject", "-noout"],shell=False,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate(csr) Get the X.509 subject from this CSR.
if out and not err:
return out @type csr: string
return None @param csr: PEM-encoded string of the CSR.
@return: a string of the subject
"""
req = M2Crypto.X509.load_request_string(csr)
return req.get_subject().as_text()
def cn(csr): def cn(csr):
"""Get the common name from this CSR. Requires there be exactly one.""" """
cns = [] Get the common name from this CSR. Requires there be exactly one CN
s = subject(csr) (of type ASN1_string)
if s:
cns = [x for x in s.rstrip().split("/") if x[:3] == "CN="] @type csr: str
if len(cns) == 1: @param csr: PEM-encoded string of the CSR.
return cns[0].split("=")[1]
return None @return: string of the first
"""
req = M2Crypto.X509.load_request_string(csr)
# Get an array of CNs
cns = req.get_subject().get_entries_by_nid(M2Crypto.X509.X509_Name.nid['CN'])
# If it's not 1, we've got problems (throw error?)
if len(cns) != 1:
return None
return cns[0].get_data().as_text()
def subject_names(csr): def subject_names(csr):
"""Get the cn and subjectAltNames from this CSR.""" """
Get the cn and subjectAltNames from this CSR.
@type csr: str
@param csr: PEM-encoded string of the CSR
@return: array of strings of subject (CN) and subject
alternative names (x509 extension)
"""
return pkcs10.subject_names(csr) return pkcs10.subject_names(csr)
def can_sign(name): def can_sign(name):