Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdlib.h"
- #include "stdio.h"
- #include "include\eTPkcs11.h"
- #include <windows.h>
- #include "base64.h"
- #include <wincrypt.h>
- using namespace std;
- #define PATH_PEM "C:\\Users\\akeela\\Desktop\\RNT\\Lab3\\coolkey.pem"
- #define PATH_CERT "C:\\Users\\akeela\\Desktop\\RNT\\Lab3\\coolcert.pfx"
- #define PASSWD "123123"
- void init();
- void leave(const char*);
- static void GetPKBlob(CK_BYTE_PTR pk, int pkSize, CK_BYTE_PTR* subject, int* subjectSize);
- static void ImportPrivateKey(const char* fileName, const char* password);
- static void ImportFile(const char* fileName,const char* label, const char* password);
- static void ExportFile(const char* fileName,const char* password);
- static void DeleteData(const char* password);
- static CK_ULONG GetFirstSlotId();
- static bool CreatePKFromBlob(CK_SESSION_HANDLE hSession, CK_BYTE_PTR key, int keySize);
- bool getPrivateKey(CK_BYTE_PTR pkfile);
- //Глобальные переменные
- CK_FUNCTION_LIST_PTR pFunctionList=NULL;
- CK_C_GetFunctionList pGFL = 0;
- bool wasInit = false;
- int main()
- {
- init();
- //char path[100];
- //char pass[20];
- ImportPrivateKey(PATH_PEM,PASSWD);
- getchar();
- leave(NULL);
- return 0;
- }
- void init()
- {
- // Загружаем dll
- HINSTANCE hLib = LoadLibraryA("etpkcs11.DLL");
- if (hLib == NULL)
- {
- leave ("Cannot load DLL.");
- }
- // Ищем точку входа для C_GetFunctionList
- (FARPROC&)pGFL= GetProcAddress(hLib, "C_GetFunctionList");
- if (pGFL == NULL)
- {
- leave ("Cannot find GetFunctionList().");
- }
- //Берем список функций
- if (CKR_OK != pGFL(&pFunctionList))
- {
- leave ("Can't get function list. \n");
- }
- // Инициализируем библиотеку PKCS#11
- //
- if (CKR_OK != pFunctionList->C_Initialize (0))
- {
- leave ("C_Initialize failed...\n");
- }
- wasInit = true;
- }
- static void leave(const char * message)
- {
- if (message) printf("%s ", message);
- if(wasInit)
- {
- // Закрываем библиотеку PKCS#11
- if (CKR_OK != pFunctionList->C_Finalize(0))
- {
- printf ("C_Finalize failed...\n");
- }
- wasInit = false;
- }
- exit(message ? -1 : 0 );
- }
- /* Extracts the private key blob from pem */
- static void GetPKBlob(CK_BYTE_PTR pk // pem файл
- , int pkSize // Размер файла
- , CK_BYTE_PTR* subject // Указатель на раскодированный закр. ключ
- , int* subjectSize // Размер закр. ключа
- ) {
- unsigned int i,size=0,count=0;
- unsigned char* current = pk;
- unsigned char* start;
- unsigned char* end;
- *subject = NULL;
- *subjectSize = 0;
- //находим начало base64 данных
- while (current[0] !='-') *current++;
- while (current[0] =='-') *current++;
- while (current[0] !='-') *current++;
- while (current[0] =='-') *current++;
- start = ++current;
- while (current[0] !='-')
- {
- if ((current[0] =='\n') || (current[0] =='-')) count++;
- *current++;
- }
- end = current;
- size = (int)(end-start)-count;
- //создаем новый массив, без мешуры
- BYTE *newbyte = new BYTE[size];
- current=start;
- for (i=0;i<size;i++)
- {
- if (current[0] =='\n') *current++;
- newbyte[i]=(BYTE)current[0];
- *current++;
- }
- *subject = base64_decode((char*)newbyte,size, (unsigned int*)subjectSize);
- }
- //чтение пем НОМЕР 2
- void readThatPEM(const char* fileName, CK_BYTE_PTR* pkfile, DWORD* pkfileSize)
- {
- HANDLE hPEM;
- hPEM = CreateFileA(fileName,
- GENERIC_READ,
- 0,
- NULL,
- OPEN_EXISTING,
- 0,
- NULL
- );
- DWORD read;
- *pkfileSize = GetFileSize(hPEM, NULL);
- *pkfile = new CK_BYTE[*pkfileSize];
- if(!(ReadFile(hPEM, *pkfile, *pkfileSize, &read, NULL)))
- printf("I HATE WINAPI!!!11");
- }
- bool getPrivateKey(CK_BYTE_PTR pkfile)
- {
- unsigned char* key = pkfile;
- if (key[0]!=0x30) return false; //неверный формат
- BYTE *modulus, *pubE, *privE,*p1, *p2, *e1, *e2,*coeff; //компоненты закр. ключа
- int modulusL, pubEL, privEL, p1L, p2L, e1L, e2L, coeffL; //длины компонентов
- //напишите более красивый парсер, если сможете
- int cur=0;
- while ((key[cur]!=0x02)||((key[cur+1]!=0x81)&&(key[cur+1]!=0x82)))
- {
- cur++;
- }
- cur++;
- if (key[cur] ==0x81) {modulusL = key[cur+1]; modulus=key+cur+2; if (key[cur+2]==0)
- {modulusL--; modulus++; cur++;} cur = cur+2+modulusL;}
- if (key[cur] ==0x82) {modulusL = key[cur+1]<<8|key[cur+2]; modulus=key+cur+3; if
- (key[cur+3]==0) {modulusL--; modulus++; cur++;} cur = cur+3+modulusL;}
- if (key[cur] !=0x02) return false; cur++;
- pubEL = key[cur]; pubE=key+cur+1; cur = cur+1+pubEL;
- if (key[cur] !=0x02) return false; cur++;
- if (key[cur] ==0x81) {privEL = key[cur+1]; privE=key+cur+2; if (key[cur+2]==0) {privEL--; privE++; cur++;}
- cur = cur+2+privEL;}
- if (key[cur] ==0x82) {privEL = key[cur+1]<<8|key[cur+2]; privE=key+cur+3; if
- (key[cur+3]==0) {privEL--; privE++; cur++;} cur = cur+3+privEL;}
- if (key[cur] !=0x02) return false; cur++;
- if ((key[cur] ==0x81)||(key[cur] ==0x80)) cur++;
- p1L = key[cur]; p1=key+cur+1; if (key[cur+1]==0) {p1L--; p1++; cur++;} cur = cur+1+p1L;
- if (key[cur] !=0x02) return false; cur++;
- if ((key[cur] ==0x81)||(key[cur] ==0x80)) cur++;
- p2L = key[cur]; p2=key+cur+1; if (key[cur+1]==0) {p2L--; p2++; cur++;} cur = cur+1+p2L;
- if (key[cur] !=0x02) return false; cur++;
- if ((key[cur] ==0x81)||(key[cur] ==0x80)) cur++;
- e1L = key[cur]; e1=key+cur+1; if (key[cur+1]==0) {e1L--; e1++; cur++;} cur = cur+1+e1L;
- if (key[cur] !=0x02) return false; cur++;
- if ((key[cur] ==0x81)||(key[cur] ==0x80)) cur++;
- e2L = key[cur]; e2=key+cur+1; if (key[cur+1]==0) {e2L--; e2++; cur++;} cur = cur+1+e2L;
- if (key[cur] !=0x02) return false; cur++;
- if ((key[cur] ==0x81)||(key[cur] ==0x80)) cur++;
- coeffL = key[cur]; coeff=key+cur+1; if (key[cur+1]==0) {coeffL--; coeff++;}
- }
- static void ImportPrivateKey(const char* fileName, const char* password)
- {
- CK_BYTE_PTR pkfile = NULL;
- DWORD pkfileSize;
- CK_BYTE_PTR subject = NULL;
- int subjSize;
- // Read the pem file
- readThatPEM(fileName, &pkfile, &pkfileSize);
- // decode base64 and extract the private key blob
- GetPKBlob((unsigned char*)pkfile, pkfileSize, &subject, &subjSize);
- getPrivateKey((unsigned char*)pkfile);
- // Find connected token
- CK_SESSION_HANDLE hSession;
- CK_SLOT_ID slotId = GetFirstSlotId();
- // login to token
- pFunctionList->C_OpenSession(slotId, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &hSession);
- pFunctionList->C_Login(hSession, CKU_USER, (LPBYTE)password, strlen(password));
- // Import the private key to the token
- CreatePKFromBlob(hSession, (unsigned char*)pkfile, pkfileSize);
- //CreatePKFromBlob();
- // Close session
- pFunctionList->C_Logout(hSession);
- pFunctionList->C_CloseSession(hSession);
- //чисти чисти чисти чисти
- if (pkfile) {
- delete[] pkfile;
- }
- }
- static void ImportFile(const char* fileName,const char* label, const char* password)
- {
- CK_BYTE_PTR file = NULL;
- DWORD fileSize;
- // Read the file
- // Find connected token
- // login to token
- // Import file to the token
- // Close session
- if (file) {
- delete[] file;
- }
- }
- static void ExportFile(const char* fileName,const char* password)
- {
- CK_BYTE_PTR file = NULL;
- DWORD fileSize;
- // Find connected token
- // login to token
- // Read file from the token
- // Save the file
- // Close session
- if (file) {
- delete[] file;
- }
- }
- static void DeleteData(const char* password)
- {
- // Find connected token
- // login to token
- // read data and delete selected
- // Close session
- }
- static CK_ULONG GetFirstSlotId()
- {
- CK_ULONG slotId = -1;
- CK_ULONG ulCount = 0;
- CK_SLOT_ID_PTR pSlotId = NULL_PTR;
- CK_ULONG i;
- if (pFunctionList->C_GetSlotList(TRUE, NULL_PTR, &ulCount) == CKR_OK)
- {
- if (ulCount > 0)
- {
- pSlotId = new CK_SLOT_ID[ulCount];
- if ((pFunctionList->C_GetSlotList(TRUE, pSlotId, &ulCount)) == CKR_OK)
- {
- for (i = 0; i < ulCount; i++)
- {
- CK_SLOT_INFO info;
- if ((pFunctionList->C_GetSlotInfo(pSlotId[i], &info)) == CKR_OK)
- {
- if (info.flags & (CKF_HW_SLOT | CKF_TOKEN_PRESENT))
- {
- slotId = pSlotId[i];
- break;
- }
- }
- }
- }
- }
- }
- if (pSlotId)
- {
- delete[] pSlotId;
- pSlotId = NULL_PTR;
- }
- return slotId;
- }
- static bool CreatePKFromBlob(CK_SESSION_HANDLE hSession, CK_BYTE_PTR key, int keySize)
- {
- CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
- CK_KEY_TYPE keyType = CKK_RSA;
- //далее нефыдоделал
- //unsigned long certCategory = 2;
- CK_BBOOL trueVal = CK_TRUE;
- CK_OBJECT_HANDLE hKeyObject;
- // ???????
- CK_ATTRIBUTE templateArray[] = { {CKA_CLASS, &keyClass, sizeof(keyClass)},
- {CKA_KEY_TYPE, &keyType, sizeof(keyType)},
- {CKA_TOKEN, &trueVal, sizeof(trueVal)},
- //{CKA_SUBJECT, subject, subjSize},
- {CKA_VALUE, (void*)key, keySize},
- //{CKA_CERTIFICATE_CATEGORY, (void*)&certCategory, sizeof(certCategory)},
- };
- int sizeOfTemplate = sizeof(templateArray) / sizeof(CK_ATTRIBUTE);
- CK_RV rv = pFunctionList->C_CreateObject(hSession, templateArray, sizeOfTemplate, &hKeyObject);
- if (rv)
- {
- return false;
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement