2007-04-10

Python utility for generating certificate

Here is a Python script that generates a certificate with various formats, including JKS and PFX. It also requires JDK and OpenSSL being installed.

-----------------------------
#!/usr/local/bin python

"""
Create a certificate with Python.
"""

import urllib, sys, getopt, os, shutil
from M2Crypto import SSL, httpslib
from M2Crypto import RSA, X509, EVP, m2, Rand, Err

keystorepass = 'secret'

def passphrase_callback(v):
return keystorepass

def generateRSAKey():
return RSA.gen_key(1024, m2.RSA_F4)

def makePKey(key):
pkey = EVP.PKey()
pkey.assign_rsa(key)
return pkey

def makeRequest(pkey, server_dns):
req = X509.Request()
# Seems to default to 0, but we can now set it as well, so just API test
req.set_version(req.get_version())
req.set_pubkey(pkey)
name = X509.X509_Name()
name.CN = server_dns
name.OU = 'My Unit'
name.O = 'My Company'
name.L = 'My City'
name.ST = 'My State'
name.C = 'US'
req.set_subject_name(name)
ext1 = X509.new_extension('Comment', 'Auto Generated')
extstack = X509.X509_Extension_Stack()
extstack.push(ext1)
req.add_extensions(extstack)
req.sign(pkey, 'md5')
return req

def sendRequest(crtreq):
# send to a web service to sign the certificate
return crtresp

def extractCert(crtresp):

crt = ''
# extract crt from the response
return crt

def createJKS(fqdn):

java_home = os.environ['JAVA_HOME']
if java_home is None:
raise 'JAVA_HOME needs to be set.'

# an empty Java keystore
jks_template = 'template.jks'
jksfile = ''.join([fqdn, '.jks'])
certfile = ''.join([fqdn, '.crt'])
keyfile = ''.join([fqdn, '.der'])
shutil.copyfile(jks_template, jksfile)

os.spawnl(os.P_WAIT, ''.join([java_home, '/bin/java.exe']), 'java', '-cp', '.', 'KeyStoreImport', jksfile, keystorepass, fqdn, certfile, keyfile, keystorepass)

def createPFX(fqdn):

openssl_home = "c:/tools/openssl"
if openssl_home is None:
raise 'openssl needs to be installed.'

certfile = ''.join([fqdn, '.crt'])
keyfile = ''.join([fqdn, '.key'])
pfxfile = ''.join([fqdn, '.pfx'])
inpass = ":".join(['pass', keystorepass])
outpass = ":".join(['pass', keystorepass])

os.spawnl(os.P_WAIT, ''.join([openssl_home, '/bin/openssl.exe']), 'openssl', 'pkcs12', '-export', '-inkey', keyfile, \
'-in', certfile, '-out', pfxfile, '-passin', inpass, '-passout', outpass)

def moveFiles(fqdn):

if os.path.isdir(fqdn):
os.rmdir(fqdn)
os.mkdir(fqdn)
shutil.move(''.join([fqdn, '.key']), fqdn)
shutil.move(''.join([fqdn, '.der']), fqdn)
shutil.move(''.join([fqdn, '.crt']), fqdn)
shutil.move(''.join([fqdn, '.jks']), fqdn)
shutil.move(''.join([fqdn, '.pfx']), fqdn)

def makeCert(fqdn):

print '####### Generate RSA Key #######'
rsa = generateRSAKey()
rsa.save_key(''.join([fqdn, '.key']), cipher='aes_256_cbc', callback=passphrase_callback)
rsa.save_key_der(''.join([fqdn, '.der']))

print '####### Generate Pub/Pri Keys #######'
pkey = makePKey(rsa)

print '####### Generate Certificate Request #######'
req = makeRequest(pkey, fqdn)

print '####### Generate Certificate Request PEM #######'
crtreq = req.as_pem()
print '####### Certificate Request #######'
print crtreq
print '####### Certificate Request #######', '\n'

crtresp = sendRequest(crtreq, fqdn)
# print '####### Certificate Response #######'
# print crtresp
# print '####### Certificate Response #######', '\n'
crtfile = open(''.join([fqdn, '.crt']), 'w')
crtfile.write(crtresp)
crtfile.close()

crtfile = open(''.join([fqdn, '.crt']), 'r')
crt = extractCert(crtfile)
print '####### Certificate #######'
print crt
print '####### Certificate #######', '\n'
crtfile.close()

crtfile = open(''.join([fqdn, '.crt']), 'w')
crtfile.write(crt)
crtfile.close()

print '####### Generate JKS #######'
createJKS(fqdn)

print '####### Generate PFX #######'
createPFX(fqdn)

print '####### Move Files #######'
moveFiles(fqdn)

print "Certificate generated"

def usage():

print "Usage:"
print "python gencrt.py -n <fqdn>"

if __name__ == '__main__':

try:
opts, args = getopt.getopt(sys.argv[1:], "hn:", ["help", "fqdn="])
except getopt.GetoptError:
usage()
sys.exit(2)

fqdn = None
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-n", "--fqdn"):
fqdn = arg

if fqdn == None:
usage()
sys.exit(2)

makeCert(fqdn)</fqdn>

9 comments:

Anonymous said...

You write very well.

Anonymous said...

Size 1/0 3/0 JHooks and big names If in a position to use the anchored method[url=http://www.coastdress4sale.co.uk/index.php]coast outlet dresses[/url] The city is bustling with a range of games for Puerto Banus hen groups to enjoyHer onscreen chemistry with the FBI agent works through film and never really gratesThose older need not worry as people ok hereCape Town is this town of fair skies

Anonymous said...

This alloաs upgraded accounts people tο try oout гegarding $.
ϲom haѕ responded to tҺe lawsuit in tɦe same manner. by simply Dɑn Holroyd
iis ɑnother personal comρuter plan thɑt uses nuclear gօеs to Һelp automatically resolve
Free оf charge - Cellular.

mƴ web blolg - solitaire download

Anonymous said...

Some applications with the 3G make use of the landscape keyboard, but
not all. The softer the leather-based, the much more expensive the wallet usually
is, according to wholesalers and merchants.

Also visit my web blog cydia sources list location

Unknown said...

jetez un coup d'œil à ce site répliques de sacs à main gucci un article KO Chrome-Hearts Dolabuy vous pouvez vérifier ici https://www .dolabuy.co

seteth said...

conseils utiles Loewe Dolabuy vérifier mon site Dolabuy YSL imp source Louis Vuitton Dolabuy

thesoez said...

j2q54g5d09 z8s69m9s15 u7h85w8a63 l5n75p2r39 a0b41x4c43 t8m82b1q55

Anonymous said...

Clifton remains tied to the New York Knicks community and today, the Sweetwater Clifton 'City Spirit' Award pays tribute to local New York heroes who have made a significant difference to the lives of others. These retros will sometimes be made to look like the originals, with Nike Air and Swoosh branding, and sometimes feature the Jumpman logo of Jordan Brand. Consisting of a simple Fendi Handbags mix of white, black, and grey fog, this Air Jordan 1 is accented by a touch of bleached coral on the Air Jordan Sale Nike Air on the tongue label as well as the insole. The Air Jordan 1 Mid often receives colorways far better than that of Christian Dior Handbags its high-top counterpart. Let's be real, 2021 was relatively lackluster as far as sneakers were concerned. The Solider was Moncler Sale always about serving LeBron and giving him another thing in his quiver he needed that wasn't in his game shoe, says Petrie. Additionally, Exclusive Golden Goose Outlet Access does not mean a pair is reserved for in a member's size, but rather assures first chance Air Jordan 4 Sale at Loewe Handbags the product. Plange remembers the profound cultural shift she sensed when she moved from her home country of Ghana to Bottega Veneta Handbags Southern California at five years old. In all seriousness, this upcoming Air Jordan 3 Retro for women captures the original 1988 colorway of Black and Cement Grey, but curiously adds a touch a gold on those aforementioned panels. I was fashion conscious. Petrie and Saint Laurent Bags LeBron wanted the X to Valentino Handbags have a visual significance as an anniversary shoe. Since then, the Air Jordan 12 has been in regular production and is a top-seller for Jordan Brand without much effort on the marketing end.

Anonymous said...

kyrie 6
supreme outlet
bape
paul george shoes
adidas yeezy