Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Starts an app locally to test it. 

4""" 

5from OpenSSL import crypto 

6 

7 

8def create_self_signed_cert(keyfile="key.pem", certfile="cert.pem", 

9 country='FR', state='Paris', location='Paris', 

10 organization='mathenjeu', cn='mathenjeu', 

11 organizational_unit_name=None, 

12 email=None, size=4096, days=365, algo="sha256", 

13 fLOG=print): 

14 """ 

15 Creates a signed certificate. 

16 

17 :param keyfile: key file 

18 :param certfile: certificate file 

19 :param country: country 

20 :param state: state 

21 :param location: location 

22 :param cn: common name 

23 :param organization: organization 

24 :param organizational_unit_name: organizational unit name (can be empty) 

25 :param email: email (can be empty) 

26 :param size: key size 

27 :param days: days it is valid 

28 :param algo: algorithm 

29 :param fLOG: logging function 

30 

31 See also `How to generate a certificate using pyOpenSSL to make it secure connection? 

32 <https://stackoverflow.com/questions/44055029/how-to-generate-a-certificate-using-pyopenssl-to-make-it-secure-connection>`_, 

33 `How to serve HTTP/2 using Python 

34 <https://medium.com/python-pandemonium/how-to-serve-http-2-using-python-5e5bbd1e7ff1>`_. 

35 

36 .. cmdref:: 

37 :title: Creates a signed certificate 

38 :cmd: -m mathenjeu create_self_signed_cert --help 

39 

40 The command line creates a certificate used later by 

41 a service such as :epkg:`hypercorn` or :epkg:`waitress`. 

42 Example:: 

43 

44 python -m mathenjeu create_self_signed_cert --keyfile=key.pem --certfile=cert.pem 

45 """ 

46 k = crypto.PKey() 

47 k.generate_key(crypto.TYPE_RSA, size) 

48 

49 cert = crypto.X509() 

50 

51 cert.get_subject().C = country 

52 cert.get_subject().ST = state 

53 cert.get_subject().L = location 

54 cert.get_subject().O = organization 

55 if organizational_unit_name: 

56 cert.get_subject().OU = organizational_unit_name 

57 cert.get_subject().CN = cn 

58 if email: 

59 cert.get_subject().emailAddress = email 

60 

61 cert.set_serial_number(1000) 

62 cert.gmtime_adj_notBefore(0) 

63 cert.gmtime_adj_notAfter(5 * days * 24 * 60 * 60) 

64 cert.set_issuer(cert.get_subject()) 

65 cert.set_pubkey(k) 

66 cert.sign(k, 'sha256') 

67 

68 with open(certfile, 'wb') as f: 

69 if fLOG: 

70 fLOG("[create_self_signed_cert] create '{0}'".format(certfile)) 

71 f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) 

72 

73 with open(keyfile, 'wb') as f: 

74 if fLOG: 

75 fLOG("[create_self_signed_cert] create '{0}'".format(keyfile)) 

76 f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))