ThalesGroup / pycryptoki

Python interface to SafeNet's PKCS11 library implementation
Apache License 2.0
60 stars 23 forks source link

How to Extract Public Key #26

Closed a6r2u8n closed 3 years ago

a6r2u8n commented 3 years ago

Is it possible to extract RSA public key ? like option 32 - OBJECT MANAGEMENT in ckdemo

astraw38 commented 3 years ago

Yes, but you'd need to do the DER encoding manually. That option does the following things:

  1. C_GetAttributeValue() to get CKA_MODULUS and CKA_PUBLIC_EXPONENT (can be done in pycryptoki va c_get_attribute_value)
  2. DER Encodes those values & write them to file.

It's an ASN.1 encoding (and there's an asn1 library in python to help you convert):

SEQUENCE
   rsaEncoding OID  # Note: this is a sequence + object ID
   BIT_STRING (KeyLen)
   SEQUENCE
     INTEGER (modulus)
     INTEGER (public exponent)

You can see a hard example of this in Microsoft's docs: https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-sequence?redirectedfrom=MSDN

Alternatively, since you can get the e/n values, you can use the cryptography library to create public numbers object directly, and then export them to whatever format you want (DER/PEM)