"""
Create certificates and private keys for the 'simple' example.
"""

from OpenSSL import crypto
from certgen import *   # yes yes, I know, I'm lazy
cakey = createKeyPair(TYPE_RSA, 2048)
careq = createCertRequest(cakey, CN='Certificate Authority')
cacert = createCertificate(careq, (careq, cakey), 0, (0, 60*60*24*365*5)) # five years

print('Creating Certificate Authority private key in "simple/CA.pkey"')
open('simple/CA.pkey', 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey).decode('utf-8'))
print('Creating Certificate Authority certificate in "simple/CA.cert"')
open('simple/CA.cert', 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cacert).decode('utf-8'))

for (fname, cname) in [('client', 'Simple Client'), ('server', 'Simple Server')]:
    pkey = createKeyPair(TYPE_RSA, 2048)
    req = createCertRequest(pkey, CN=cname)
    cert = createCertificate(req, (cacert, cakey), 1, (0, 60*60*24*365*5)) # five years

    print('Creating Certificate %s private key in "simple/%s.pkey"' % (fname, fname))
    open('simple/%s.pkey' % (fname,), 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
    print('Creating Certificate %s certificate in "simple/%s.cert"' % (fname, fname))
    open('simple/%s.cert' % (fname,), 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))

@@ -399,24 +399,29 @@
 /CA.pkey%22')%0A
+with 
 open('simple
@@ -431,24 +431,46 @@
 .pkey', 'w')
+ as capkey:%0A    capkey
 .write(crypt
@@ -604,16 +604,21 @@
 cert%22')%0A
+with 
 open('si
@@ -632,24 +632,38 @@
 .cert', 'w')
+ as ca:%0A    ca
 .write(crypt
@@ -1066,32 +1066,37 @@
 me, fname))%0A    
+with 
 open('simple/%25s.
@@ -1109,32 +1109,62 @@
 %25 (fname,), 'w')
+ as leafpkey:%0A        leafpkey
 .write(crypto.du
@@ -1311,16 +1311,21 @@
 e))%0A    
+with 
 open('si
@@ -1354,16 +1354,46 @@
 ,), 'w')
+ as leafcert:%0A        leafcert
 .write(c
@@ -1439,28 +1439,29 @@
 PEM, cert).decode('utf-8'))%0A
+%0A

convert cert and private key creation to use context managers