cert_gen.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #import cryptography
  2. from cryptography.hazmat.backends import default_backend
  3. from cryptography.hazmat.primitives import serialization
  4. from cryptography.hazmat.primitives.asymmetric import rsa
  5. from cryptography import x509
  6. from cryptography.x509.oid import NameOID
  7. from cryptography.hazmat.primitives import hashes
  8. import datetime
  9. #c=u"GB"
  10. #st=u"England"
  11. #l=u"Manchester"
  12. #o=u'Jisc'
  13. #ou=u''
  14. #servername = u"jadzia.mcc.ac.uk"
  15. #crldp=u'http://somewhere.example.com/awebserver'
  16. #passphrase=b'somethingsecure'
  17. def gen_cakey(bits):
  18. key = rsa.generate_private_key(
  19. public_exponent=65537,
  20. key_size=int(bits),
  21. backend=default_backend()
  22. )
  23. return key
  24. def write_key_encrypted(filename,key,passphrase):
  25. with open(filename, "wb") as f:
  26. f.write(key.private_bytes(
  27. encoding=serialization.Encoding.PEM,
  28. format=serialization.PrivateFormat.TraditionalOpenSSL,
  29. encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
  30. ))
  31. def output_key_encrypted(key,passphrase):
  32. return key.private_bytes(
  33. encoding=serialization.Encoding.PEM,
  34. format=serialization.PrivateFormat.TraditionalOpenSSL,
  35. encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
  36. )
  37. def write_key(filename,key):
  38. with open(filename, "wb") as f:
  39. f.write(key.private_bytes(
  40. encoding=serialization.Encoding.PEM,
  41. format=serialization.PrivateFormat.TraditionalOpenSSL,
  42. encryption_algorithm=serialization.NoEncryption(),
  43. ))
  44. def output_key(key):
  45. return key.private_bytes(
  46. encoding=serialization.Encoding.PEM,
  47. format=serialization.PrivateFormat.TraditionalOpenSSL,
  48. encryption_algorithm=serialization.NoEncryption(),
  49. )
  50. def build_name(c,st,l,o,ou,cn):
  51. array = []
  52. if (c):
  53. array.append(x509.NameAttribute(NameOID.COUNTRY_NAME,c))
  54. if (st):
  55. array.append(x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME,st))
  56. if (l):
  57. array.append(x509.NameAttribute(NameOID.LOCALITY_NAME,l))
  58. if (o):
  59. array.append(x509.NameAttribute(NameOID.ORGANIZATION_NAME,o))
  60. if (ou):
  61. array.append(x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME,ou))
  62. if (cn):
  63. array.append(x509.NameAttribute(NameOID.COMMON_NAME,cn))
  64. return x509.Name(array)
  65. def build_rootca(key,subject,issuer,duration):
  66. cert = x509.CertificateBuilder().subject_name(
  67. subject
  68. ).issuer_name(
  69. issuer
  70. ).public_key(
  71. key.public_key()
  72. ).serial_number(
  73. x509.random_serial_number()
  74. ).not_valid_before(
  75. datetime.datetime.utcnow()
  76. ).not_valid_after(
  77. datetime.datetime.utcnow() + datetime.timedelta(days=duration)
  78. ).add_extension(
  79. # x509.AuthorityKeyIdentifier(public_key,[x509.DirectoryName(caissuer)],caserial),
  80. x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),
  81. critical=False,
  82. ).add_extension(
  83. x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
  84. critical=False,
  85. ).add_extension(
  86. x509.BasicConstraints(True,None),
  87. critical=True,
  88. ).sign(key, hashes.SHA256(), default_backend())
  89. return cert
  90. def build_servercert(key,root,csr,name,crldp,duration):
  91. builder = x509.CertificateBuilder().subject_name(
  92. csr.subject
  93. ).issuer_name(
  94. root.issuer
  95. ).public_key(
  96. csr.public_key()
  97. ).serial_number(
  98. x509.random_serial_number()
  99. ).not_valid_before(
  100. datetime.datetime.utcnow()
  101. ).not_valid_after(
  102. datetime.datetime.utcnow() + datetime.timedelta(days=duration)
  103. ).add_extension(
  104. x509.KeyUsage(True,True,True,False,False,False,False,False,False),
  105. critical=True,
  106. ).add_extension(
  107. x509.SubjectAlternativeName([x509.DNSName(name)]),
  108. critical=False,
  109. ).add_extension(
  110. x509.BasicConstraints(False,None),
  111. critical=True,
  112. ).add_extension(
  113. x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.SERVER_AUTH]),
  114. critical=False,
  115. ).add_extension(
  116. x509.AuthorityKeyIdentifier.from_issuer_public_key(root.public_key()),
  117. critical=False,
  118. ).add_extension(
  119. x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
  120. critical=False,
  121. )
  122. if ( crldp ):
  123. builder = builder.add_extension(
  124. x509.CRLDistributionPoints(
  125. [x509.DistributionPoint(
  126. [x509.UniformResourceIdentifier(crldp)],
  127. None,
  128. None,
  129. None
  130. )
  131. ]
  132. ),
  133. critical=False,
  134. )
  135. cert = builder.sign(key, hashes.SHA256(), default_backend())
  136. return cert
  137. def build_csr(key,subject,name):
  138. csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name(
  139. subject
  140. )).add_extension(
  141. x509.SubjectAlternativeName([
  142. x509.DNSName(name),
  143. ]),
  144. critical=False,
  145. # Sign the CSR with our private key.
  146. ).sign(key, hashes.SHA256(), default_backend())
  147. return csr
  148. def build_crl(key,issuer,duration):
  149. builder = x509.CertificateRevocationListBuilder()
  150. builder = builder.issuer_name(issuer)
  151. builder = builder.last_update(datetime.datetime.today())
  152. builder = builder.next_update(datetime.datetime.today() + datetime.timedelta(days=duration))
  153. revoked_cert = x509.RevokedCertificateBuilder().serial_number(
  154. x509.random_serial_number()
  155. ).revocation_date(
  156. datetime.datetime.today()
  157. ).build(default_backend())
  158. # builder = builder.add_revoked_certificate(revoked_cert)
  159. crl = builder.sign(
  160. private_key=key, algorithm=hashes.SHA256(),
  161. backend=default_backend()
  162. )
  163. return crl
  164. def write_cert(filename,cert):
  165. with open(filename, "wb") as f:
  166. f.write(cert.public_bytes(serialization.Encoding.PEM))
  167. def output_cert(cert):
  168. return cert.public_bytes(serialization.Encoding.PEM)