pykcs_tls_request.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. '''Created Oct 13, 2021 Levi'''
  2. import os
  3. import ssl
  4. import tempfile
  5. import urllib.request
  6. import asn1crypto.pem
  7. import keyring
  8. import PyKCS11
  9. from PyKCS11.LowLevel import (CKA_CLASS, CKO_CERTIFICATE,
  10. CKA_VALUE, CKA_ID, CKM_SHA1_RSA_PKCS,
  11. CKO_PRIVATE_KEY, CKM_SHA256_RSA_PKCS,
  12. CKF_SERIAL_SESSION, CKF_RW_SESSION,
  13. CKA_LABEL, CKA_VALUE, CKA_MODULUS)
  14. import requests
  15. lib = PyKCS11.PyKCS11Lib()
  16. lib.load()
  17. keyID = (0x38, 0x7b, 0x4b, 0x49, 0xe2, 0xe7, 0x10, 0x4f, 0x60, 0x15, 0xc1, 0x42, 0x38, 0x6c, 0x3d, 0x41, 0x43, 0x5e, 0x91, 0x9b,)
  18. token_present = True
  19. slot = lib.getSlotList(tokenPresent=True)[0]
  20. session = lib.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
  21. session.login(keyring.get_password('sig', 'token'))
  22. pkcs11_certificates = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE), (CKA_LABEL, 'Levente Marton')])
  23. # assert len(pkcs11_certificates) == 1
  24. pkcs11_cert = pkcs11_certificates[0]
  25. privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_ID, keyID)])[0]
  26. modulus = session.getAttributeValue(privKey, [CKA_MODULUS])[0]
  27. priv_key_dct = privKey.to_dict()
  28. # print(pkcs11_cert)
  29. print(privKey)
  30. pkcs11_cert_dct = pkcs11_cert.to_dict()
  31. der_encoded_certificate = bytes(pkcs11_cert_dct['CKA_VALUE'])
  32. # print(der_encoded_certificate)
  33. pem_armored_certificate = asn1crypto.pem.armor("CERTIFICATE",
  34. der_encoded_certificate)
  35. pem_armored_priv_key = asn1crypto.pem.armor("PRIVATE KEY",
  36. bytes(modulus))
  37. certfile = 'cert.pem'
  38. # privkey = 'privkey.key'
  39. # with open(certfile, 'wb') as certfile_handle:
  40. # certfile_handle.write(pem_armored_certificate)
  41. # with open(privkey, 'wb') as certfile_handle:
  42. # certfile_handle.write(pem_armored_priv_key)
  43. # try:
  44. session.logout()
  45. session.closeSession()
  46. cookie = {'LastMRH_Session': '7309fec2; F5_ST=1z1z1z1637062323z-1',
  47. 'MRHSession': '12f446c0f7d6dacc00657e8d7309fec2'}
  48. sslctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
  49. sslctx.load_cert_chain('cert.pem')
  50. # except Exception as exc_:
  51. # print(exc_)
  52. # finally:
  53. # r = requests.get('https://decl.anaf.mfinante.gov.ro/WAS6DUS/', cookies=cookie)
  54. # print(r.status_code)