static void DumpCardDataObjects() { PKCS11.Initialize("etoken.dll"); PKCS11.Slot[] slots = PKCS11.GetSlotList(true); if (slots.Length > 0) { PKCS11.Slot slot = slots[0]; PKCS11.Session session = PKCS11.OpenSession(slot, PKCS11.CKF_RW_SESSION | PKCS11.CKF_SERIAL_SESSION); int loginResult = session.Login(PKCS11.CKU_USER, null); if (loginResult == PKCS11.CKR_OK || loginResult == PKCS11.CKR_USER_ALREADY_LOGGED_IN) { Console.WriteLine("PIN was correct"); PKCS11.Object[] dataObjects = session.FindObjects(new PKCS11.Attribute[] { new PKCS11.Attribute(PKCS11.CKA_TOKEN, true), new PKCS11.Attribute(PKCS11.CKA_CLASS, PKCS11.CKO_DATA), }); DataObjectStore dataObjectStore = new DataObjectStore(); Console.WriteLine("\nDump Data Objects"); Console.WriteLine("------------------------------------------------------------"); foreach (PKCS11.Object dataObject in dataObjects) { DataObject persistData = new DataObject(); persistData.cka_class = (int)dataObject.Get(session, PKCS11.CKA_CLASS); persistData.cka_token = (bool)dataObject.Get(session, PKCS11.CKA_TOKEN); persistData.cka_private = (bool)dataObject.Get(session, PKCS11.CKA_PRIVATE); persistData.cka_label = (string)dataObject.Get(session, PKCS11.CKA_LABEL); try { persistData.cka_application = (string)dataObject.Get(session, PKCS11.CKA_APPLICATION); } catch (Exception e) { persistData.cka_application = ""; } try { persistData.cka_value = ByteArrayToHex((byte[])dataObject.Get(session, PKCS11.CKA_VALUE)); } catch (Exception e) { persistData.cka_value = ""; } Console.WriteLine("CKA_CLASS: " + persistData.cka_class); Console.WriteLine("CKA_TOKEN: " + persistData.cka_token); Console.WriteLine("CKA_PRIVATE: " + persistData.cka_private); Console.WriteLine("CKA_LABEL: " + persistData.cka_label); Console.WriteLine("CKA_APPLICATION: " + persistData.cka_application); Console.WriteLine("CKA_VALUE: " + (persistData.cka_value.Length >= 40 ? persistData.cka_value.Substring(0, 40) + "..." : persistData.cka_value) + "\n"); dataObjectStore.objects.Add(persistData); } BackupDataObjects(dataObjectStore); } else { Console.WriteLine("PIN was not correct"); } session.Close(); PKCS11.Finalize(); } else { Console.WriteLine("Please connect a token and try again."); } }
static void BackupDataObjects(DataObjectStore dataObjectStore) { Stream fileStream = File.Create(FILE_PATH); BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(fileStream, dataObjectStore); fileStream.Close(); Console.WriteLine("Smartcard backed up to " + FILE_PATH); }