forked from kuronosec/zk-firma-digital
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcertificate.py
74 lines (63 loc) · 2.64 KB
/
certificate.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
# Import necessary libraries
import pprint
import os
import logging
from asn1crypto import pem, x509
from PyKCS11 import *
from configuration import Configuration
# This class interacts with the Smart Card and extracts the autentication certificate
class Certificate:
def __init__(self, pin):
"""
Initialize stuff
"""
self.config = Configuration()
self.user_path = self.config.user_path
self.credentials_path = self.config.credentials_path
self.pin = pin
# Check what operation system we re running on
if os.name == 'nt':
self.library_path = 'C:/Windows/System32/asepkcs.dll'
# Linux
else:
self.library_path = '/usr/lib/x64-athena/libASEP11.so'
def get_certificates(self):
"""
Try to read the smart card to get the stored public certificates
"""
pkcs11 = PyKCS11Lib()
try:
pkcs11.load(self.library_path)
except PyKCS11Error as error:
message = "Hubo un error al cargar la libreria de la smart card"
logging.error(message+" "+str(error), exc_info=True)
return False, message
session = None
try:
session = pkcs11.openSession(0, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login(self.pin)
except PyKCS11Error as error:
message = """Hubo un error al leer la tarjeta,\
por favor verifique que esta conectada correctamente\
y que ingreso el pin correcto."""
logging.error(message+" "+str(error), exc_info=True)
return False, message
result = []
certs = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE)])
# Extract the certificates to be used later
for cert in certs:
cka_value, cka_id = session.getAttributeValue(cert, [CKA_VALUE, CKA_ID])
cert_der = bytes(cka_value)
cert = x509.Certificate.load(cert_der)
common_name = cert.native["tbs_certificate"]["subject"]["common_name"]
if "AUTENTICACION" in common_name:
result.append(common_name)
if not os.path.exists(self.credentials_path):
os.makedirs(self.credentials_path)
# cert is an instance of x509.Certificate
with open(self.config.certificate_path, 'wb') as f:
pprint.pprint(cert.native["tbs_certificate"]["subject"])
der_bytes = cert.dump()
pem_bytes = pem.armor('CERTIFICATE', der_bytes)
f.write(pem_bytes)
return True, result