1
|
1 |
|
import os |
2
|
1 |
|
|
3
|
1 |
|
from cryptography import x509 |
4
|
1 |
|
from cryptography.hazmat.backends import default_backend |
5
|
1 |
|
from cryptography.hazmat.primitives import serialization |
6
|
|
|
from cryptography.hazmat.primitives import hashes |
7
|
|
|
from cryptography.hazmat.primitives.asymmetric import padding |
8
|
1 |
|
|
9
|
1 |
|
|
10
|
1 |
|
def load_certificate(path): |
11
|
1 |
|
_, ext = os.path.splitext(path) |
12
|
1 |
|
with open(path, "br") as f: |
13
|
1 |
|
if ext == ".pem": |
14
|
1 |
|
return x509.load_pem_x509_certificate(f.read(), default_backend()) |
15
|
1 |
|
else: |
16
|
|
|
return x509.load_der_x509_certificate(f.read(), default_backend()) |
17
|
1 |
|
|
18
|
1 |
|
|
19
|
1 |
|
def x509_from_der(data): |
20
|
|
|
if not data: |
21
|
|
|
return None |
22
|
1 |
|
return x509.load_der_x509_certificate(data, default_backend()) |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
def load_private_key(path): |
26
|
|
|
with open(path, "br") as f: |
27
|
|
|
return serialization.load_pem_private_key(f.read(), password=None, backend=default_backend()) |
28
|
|
|
|
29
|
|
|
|
30
|
1 |
|
def der_from_x509(certificate): |
31
|
|
|
if certificate is None: |
32
|
|
|
return b"" |
33
|
|
|
return certificate.public_bytes(serialization.Encoding.DER) |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
def sign_sha1(private_key, data): |
37
|
|
|
signer = private_key.signer( |
38
|
|
|
padding.PKCS1v15(), |
39
|
1 |
|
hashes.SHA1() |
40
|
|
|
) |
41
|
|
|
signer.update(data) |
42
|
|
|
return signer.finalize() |
43
|
|
|
|
44
|
|
|
|
45
|
|
|
def encrypt_basic256(public_key, data): |
46
|
1 |
|
ciphertext = public_key.encrypt( |
47
|
|
|
data, |
48
|
|
|
padding.OAEP( |
49
|
|
|
mgf=padding.MGF1(algorithm=hashes.SHA256()), |
50
|
|
|
algorithm=hashes.SHA256(), |
51
|
|
|
label=None) |
52
|
|
|
) |
53
|
|
|
return ciphertext |
54
|
|
|
|
55
|
1 |
|
|
56
|
|
|
if __name__ == "__main__": |
57
|
|
|
# Convert from PEM to DER |
58
|
|
|
cert = load_certificate("../examples/server_cert.pem") |
59
|
|
|
#rsa_pubkey = pubkey_from_dercert(der) |
60
|
|
|
rsa_privkey = load_private_key("../examples/mykey.pem") |
61
|
|
|
|
62
|
|
|
from IPython import embed |
63
|
|
|
embed() |
64
|
|
|
|