-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcert_utils.py
More file actions
237 lines (193 loc) · 6.44 KB
/
Copy pathcert_utils.py
File metadata and controls
237 lines (193 loc) · 6.44 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
import datetime
from base64 import b64encode, b64decode
class FakePublicKey():
"""
This is a hack to encapsulate user-defined public key into RSA key object,
unfortunately the key must be odd.
"""
def __init__(self, pub_key=None):
self._key = None
if pub_key != None:
self.set_key(pub_key)
def set_key(self, pub_key):
key_size = 1000 # Work around with odd numbers.
if pub_key % 2 == 0: # If even key then remove 1 and add it to key size.
key_size += 1
pub_key -= 1
self._key = rsa.generate_private_key(
public_exponent=pub_key,
key_size=key_size,
backend=default_backend()).public_key()
def get_key(self):
return self._key
def get_key_val(self):
return self._key.public_numbers().e + self._key.key_size - 1000 # Work around to set even key.
def get_fake_key_val(key):
return key.public_numbers().e + key.key_size - 1000 # Work around to set even key.
def cert_build_signed(ca_priv_key, pub_key_to_store, domain):
"""
Returns a certificate signed by ca_priv_key, containing pub_key_to_store
"""
one_day = datetime.timedelta(1, 0, 0)
builder = x509.CertificateBuilder()
builder = builder.subject_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'samir&ali.io'),
]))
builder = builder.issuer_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, domain),
]))
builder = builder.not_valid_before(datetime.datetime.today() - one_day)
builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30))
builder = builder.serial_number(x509.random_serial_number())
builder = builder.public_key(pub_key_to_store)
builder = builder.add_extension(
x509.SubjectAlternativeName(
[x509.DNSName(u'samir&ali.io')]
),
critical=False
)
builder = builder.add_extension(
x509.BasicConstraints(ca=False, path_length=None), critical=True,
)
certificate = builder.sign(
private_key=ca_priv_key, algorithm=hashes.SHA256(),
backend=default_backend()
)
return certificate
def cert_get_pub_key(cert):
"""
Returns public_key from x.509 certificate.
"""
return cert.public_key()
def cert_get_host(cert):
"""
Returns hostname from certificate.
"""
return cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
def cert_write(path, cert):
"""
Saves certificate as PEM.
"""
with open(path, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
def cert_load(path):
"""
Returns certificate from PEM file.
"""
cert = x509.load_pem_x509_certificate(open(path, 'rb').read(), default_backend())
return cert
def cert_from_bytes(bytes):
"""
Returns cert from bytes.
"""
return x509.load_pem_x509_certificate(bytes, default_backend())
def cert_to_bytes(cert):
"""
Returns bytes from cert.
"""
return cert.public_bytes(serialization.Encoding.PEM)
def cert_validate_signature(cert, pub_key):
"""
Returns True if cert is signed by CA's private key given CA's public_key = pub_key, otherwise,
it returns False.
"""
try:
pub_key.verify(cert.signature, cert.tbs_certificate_bytes, padding.PKCS1v15(),
cert.signature_hash_algorithm)
return True
except Exception:
return False
def private_key_load(path):
"""
Returns private key from PEM file.
"""
with open(path, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
return private_key
def private_key_write(path, key):
"""
Writes private key to a PEM file.
"""
with open(path, "wb") as f:
f.write(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
))
def public_key_write(path, key):
"""
Writes public key to a PEM file.
"""
with open(path, "wb") as f:
f.write(key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
)
def public_key_load(path):
"""
Returns public key PEM file.
"""
return serialization.load_pem_public_key(open(path, 'rb').read(), default_backend())
def public_key_to_bytes(key):
"""
Returns public key bytes.
"""
return key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
def public_key_from_bytes(bytes):
"""
Returns public key from bytes.
"""
return serialization.load_pem_public_key(bytes, default_backend())
def public_key_encrypt(msg, key):
"""
Returns Encrypted message using key.
"""
ciphertext = key.encrypt(
msg.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return b64encode(ciphertext)
def private_key_decrypt(ciphertext, key):
"""
Returns Encrypted message using key.
"""
ciphertext = b64decode(ciphertext)
message = (key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
))
return message.decode()
if __name__ == "__main__":
private_key = rsa.generate_private_key(
public_exponent=16111995,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key() # Public key to sign the certificate
key = 10 # fake key to store, for example el gammal key, unfortunately must be odd...
fake_key = FakePublicKey(key)
cert = cert_build_signed(private_key, fake_key.get_key(), "ali")
print(cert_validate_signature(cert, public_key))
print(fake_key.get_key_val()) # Check the fake key we attached to the certificate