pykcs11_gen.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. '''Created Oct 13, 2021 Levi'''
  2. import binascii
  3. import keyring
  4. from PyKCS11 import *
  5. from PyKCS11.LowLevel import (CKA_CLASS, CKO_CERTIFICATE,
  6. CKA_VALUE, CKA_ID, CKM_SHA1_RSA_PKCS,
  7. CKO_PRIVATE_KEY, CKM_SHA256_RSA_PKCS,
  8. CKF_SERIAL_SESSION, CKF_RW_SESSION,
  9. CKA_LABEL, CKA_VALUE)
  10. # the key_id has to be the same for both objects
  11. key_id = (0x38, 0x7b, 0x4b, 0x49, 0xe2, 0xe7, 0x10, 0x4f, 0x60, 0x15, 0xc1, 0x42, 0x38, 0x6c, 0x3d, 0x41, 0x43, 0x5e, 0x91, 0x9b,)
  12. lib = PyKCS11.PyKCS11Lib()
  13. lib.load()
  14. # get 1st slot
  15. slot = lib.getSlotList(tokenPresent=True)[0]
  16. session = lib.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
  17. session.login(keyring.get_password('sig', 'token'))
  18. pubTemplate = [
  19. (CKA_CLASS, CKO_PUBLIC_KEY),
  20. (CKA_TOKEN, CK_TRUE),
  21. (CKA_PRIVATE, CK_FALSE),
  22. (CKA_MODULUS_BITS, 0x0400),
  23. (CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)),
  24. (CKA_ENCRYPT, CK_TRUE),
  25. (CKA_VERIFY, CK_TRUE),
  26. (CKA_VERIFY_RECOVER, CK_TRUE),
  27. (CKA_WRAP, CK_TRUE),
  28. (CKA_LABEL, "Levente Marton"),
  29. (CKA_ID, key_id)
  30. ]
  31. privTemplate = [
  32. (CKA_CLASS, CKO_PRIVATE_KEY),
  33. (CKA_TOKEN, CK_TRUE),
  34. (CKA_PRIVATE, CK_TRUE),
  35. (CKA_DECRYPT, CK_TRUE),
  36. (CKA_SIGN, CK_TRUE),
  37. (CKA_SIGN_RECOVER, CK_TRUE),
  38. (CKA_UNWRAP, CK_TRUE),
  39. (CKA_ID, key_id)
  40. ]
  41. pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY), (CKA_ID, key_id)])[0]
  42. privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_ID, key_id)])[0]
  43. modulus = session.getAttributeValue(privKey, [CKA_MODULUS])[0]
  44. # print("\nmodulus: {}".format(bytes(modulus)))
  45. (pubKey, privKey) = session.generateKeyPair(pubTemplate, privTemplate)
  46. #
  47. print(bytes(privKey))
  48. # logout
  49. session.logout()
  50. session.closeSession()