-
Notifications
You must be signed in to change notification settings - Fork 1
/
self_signed_x509.py
187 lines (142 loc) · 7.06 KB
/
self_signed_x509.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from datetime import datetime, timedelta
import os
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
def mk_ca_issuer(common_name="Roles Anywhere ROOT CA"):
"""
Our default CA issuer name.
"""
issuer = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Maryland"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Rockville"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Cloudbolt Software"),
])
return issuer
def generate_self_signed_certificate(to_time, from_time, cert_dir):
"""
Generates self signed certificate (X509 Root CA)
:param to_time: not available certificate after the time
:param from_time: not available certificate before the time
:param cert_dir: save root cert and key in dir
:returns: generated private key and certificate pair
"""
# generate rsa private key
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
# subject and issuer are always the same.
subject = mk_ca_issuer()
issuer = subject
# path_len=0 means this cert can only sign itself, not other certs.
basic_contraints = x509.BasicConstraints(ca=True, path_length=0)
subject_ext = x509.SubjectKeyIdentifier.from_public_key(private_key.public_key())
key_usage_ext = x509.KeyUsage(digital_signature=True, key_encipherment=False, key_cert_sign=True,
key_agreement=False, content_commitment=False, data_encipherment=False,
crl_sign=True, encipher_only=False, decipher_only=False)
authority_key_ext = x509.AuthorityKeyIdentifier.from_issuer_public_key(private_key.public_key())
# Used to build the root CA certificate
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(from_time)
.not_valid_after(to_time)
.add_extension(basic_contraints, True)
.add_extension(key_usage_ext, True)
.add_extension(subject_ext, False)
.add_extension(authority_key_ext, False)
.sign(private_key, hashes.SHA256())
)
cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM).decode("utf-8")
with open(cert_dir+'root-cert.pem', 'w') as f:
f.write(cert_pem)
print("*****************Root CA**********************")
print(cert_pem)
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
).decode("utf-8")
with open(cert_dir+'root-key.pem', 'w') as f:
f.write(private_key_pem)
print("*****************Root CA Private Key**********************")
print(private_key_pem)
return {'certificate': cert_pem, 'private_key': private_key_pem}
def generate_client_certificate(root_cert, root_private_key, from_time, to_time, cert_dir):
"""
Generate Client Certificate
:param root_cert: Root CA
:param root_private_key: private key of Root CA
:param to_time: not available certificate after the time
:param from_time: not available certificate before the time
:param cert_dir: save client cert, chain and key in dir
:returns: generated private key and certificate pair
"""
if not isinstance(root_private_key, rsa.RSAPrivateKey):
root_private_key = serialization.load_pem_private_key(root_private_key.encode("utf-8"), None)
if not isinstance(root_cert, x509.CertificateBuilder):
root_cert = x509.load_pem_x509_certificate(root_cert.encode("utf-8"))
common_name="Roles Anywhere Client"
# subject and issuer are always the same.
subject = mk_ca_issuer(common_name)
# path_len=0 means this cert can only sign itself, not other certs.
basic_contraints = x509.BasicConstraints(ca=False, path_length=None)
key_usage_ext = x509.KeyUsage(digital_signature=True, key_encipherment=True, key_cert_sign=False,
key_agreement=False, content_commitment=False, data_encipherment=True,
crl_sign=False, encipher_only=False, decipher_only=False)
authority_key_ext = x509.AuthorityKeyIdentifier.from_issuer_public_key(root_cert.public_key())
# Used to build client csr
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.add_extension(basic_contraints, True)
.add_extension(key_usage_ext, True)
.add_extension(authority_key_ext, False)
.sign(root_private_key, hashes.SHA256())
)
csr_pem = csr.public_bytes(encoding=serialization.Encoding.PEM).decode("utf-8")
with open(cert_dir+'client-csr.pem', 'w') as f:
f.write(csr_pem)
print("******************Client Certificate Chain**********************")
print(csr_pem)
# Used to build client certificate
builder = x509.CertificateBuilder(
issuer_name=root_cert.issuer,
subject_name=csr.subject,
public_key=csr.public_key(),
not_valid_before=from_time,
not_valid_after=to_time,
extensions=csr.extensions,
serial_number=root_cert.serial_number,
)
certificate = builder.sign(
private_key=root_private_key, algorithm=hashes.SHA256()
).public_bytes(serialization.Encoding.PEM).decode("utf-8")
with open(cert_dir+'client-cert.pem', 'w') as f:
f.write(certificate)
print("*******************Client Certificate***********************")
print(certificate)
private_key_pem = root_private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
).decode("utf-8")
with open(cert_dir+'client-key.pem', 'w') as f:
f.write(private_key_pem)
print("*****************Client Private Key**********************")
print(private_key_pem)
return {'client_cerfiticate':certificate,'client_cerfiticate_chain':csr_pem, "private_key": private_key_pem}
if __name__ == "__main__":
cert_dir = os.path.abspath(os.getcwd()) + "/certificates_data/"
if not os.path.isdir(cert_dir):
os.makedirs(cert_dir) # create dir if not exist
from_time = datetime.utcnow()
to_time = from_time + timedelta(days=10*365)
x509_data = generate_self_signed_certificate(to_time, from_time, cert_dir)
client_ca_data = generate_client_certificate(x509_data['certificate'],
x509_data['private_key'], from_time, to_time, cert_dir)