首页 > 其他分享 >代码链接

代码链接

时间:2024-04-10 11:11:07浏览次数:24  
标签:CK rv 代码 CKR PTR printf NULL 链接

EncryptFile.sln
#include "generic.h"
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool EncryptFile(const string &strSource,
		const string &strDestination,
		const string &strPassword); 

//--------------------------------------------------------------------
//   Begin main.

void main(void)
{
	char szSrcFile[1024] = {0};		//sourcefile
	char szTgtFile[1024] = {0};		//encryptfile
	char szPassword[1024] = {0};	//password

	printf("\nEncrypt a file.\n\nEnter the name of the file to be encrypt:\n");
	scanf("%s", szSrcFile);

	printf("Enter the name of the output file:\n");
	scanf("%s", szTgtFile);

	printf("Enter the password to encrypt the file:\n");
	scanf("%s", szPassword);

	if(EncryptFile(szSrcFile, szTgtFile, szPassword))
	{
		printf("Encrypt file successfully.\n");
	}
	else
	{
		printf("Encrypt file failed.\n");
	}
}

//--------------------------------------------------------------------
//   Code for the function EncryptFile called by main.
bool EncryptFile(const string &strSource,
		const string &strDestination,
		const string &strPassword)
{
	//--------------------------------------------------------------------
	//   Declare and initialize local variables.

	FILE *hSource = NULL;
	FILE *hDestination = NULL;

	HCRYPTPROV hCryptProv = NULL;
	HCRYPTKEY hKey = NULL;
	HCRYPTHASH hHash = NULL;

	//--------------------------------------------------------------------
	// Open source file. 
	BeginAction("Open source file for read");
	if(NULL != (hSource = fopen(strSource.c_str(), "rb")))
	{
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	} 

	//--------------------------------------------------------------------
	// Open destination file. 
	BeginAction("Open target file for write");
	if(NULL != (hDestination = fopen(strDestination.c_str(), "wb")))
	{
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	}

	// Get a CSP handle.
	BeginAction("CryptAcquireContext()");
	if(CryptAcquireContext(&hCryptProv,
			TEST_CONTAINER,
			CSP_NAME,
			PROV_RSA_FULL,
			0))
	{
		ActionSuccess();
	}
	else // Container does not exists, let us create a new one.
	{
		ActionFailed(GetLastError());

		BeginAction("CryptAcquireContext() CRYPT_NEWKEYSET");
		if(CryptAcquireContext(&hCryptProv,
				TEST_CONTAINER,
				CSP_NAME,
				PROV_RSA_FULL,
				CRYPT_NEWKEYSET))
		{
			ActionSuccess();
		}
		else
		{
			ActionFailed(GetLastError());
			return FALSE;
		}
	}

	HCRYPTPROV_Holder holder(hCryptProv);

	BeginAction("CryptCreateHash()");
	if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash))		
	{
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	}  

	BeginAction("CryptHashData()");
	if(CryptHashData(hHash,										
			(BYTE *) strPassword.c_str(),
			strPassword.length(),
			0))
	{
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	}

	BeginAction("CryptDeriveKey()");							
	if(CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey))
	{
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	}

	BeginAction("CryptDestroyHash()");							
	if(CryptDestroyHash(hHash))
	{
		hHash = NULL; 
		ActionSuccess();
	}
	else
	{
		ActionFailed(GetLastError());
		return FALSE;
	}

	DWORD dwBlockLen = 0;
	DWORD dwBufferLen = 0;
	DWORD dwCount = 0;

	dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; 

	//--------------------------------------------------------------------
	// Determine the block size. If a block cipher is used, 
	// it must have room for an extra block. 

	if(ENCRYPT_BLOCK_SIZE > 1)
	{
		dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
	}
	else
	{
		dwBufferLen = dwBlockLen;
	} 

	vector<BYTE> pbBuffer;
	pbBuffer.resize(dwBufferLen);

	//--------------------------------------------------------------------
	// In a do loop, encrypt the source file and write to the source file. 
	do
	{
		//--------------------------------------------------------------------
		// Read up to dwBlockLen bytes from the source file. 
		dwCount = fread(&pbBuffer[0], 1, dwBlockLen, hSource); 
		if(ferror(hSource))
		{
			ShowSysError("Read plain text", GetLastError());
			return FALSE;
		}
		//--------------------------------------------------------------------
		// Encrypt
		if(!CryptEncrypt(hKey,
					0,
					feof(hSource),		//file end
					0,
					&pbBuffer[0],		// [in] sourcefile; [out] encryptdata
					&dwCount,			//encryptdatalength
					dwBufferLen))		// encrypt data length
		{
			ShowSysError("CryptEncrypt()", GetLastError());
			return FALSE;
		} 

		//--------------------------------------------------------------------
		// Write data to the destination file. 
		fwrite(&pbBuffer[0], 1, dwCount, hDestination); 
		if(ferror(hDestination))
		{
			ShowSysError("Write cipher text", GetLastError());
			return FALSE;
		}
	}
	while(!feof(hSource)); 
	//--------------------------------------------------------------------
	//  End the do loop when the last block of the source file has been
	//  read, encrypted, and written to the destination file.

	//--------------------------------------------------------------------
	// Close files.
	if(hSource)
	{
		fclose(hSource);
	} 
	if(hDestination)
	{
		fclose(hDestination);
	} 

	if(hKey)
	{
		CryptDestroyKey(hKey);
	} 

	return TRUE;
} // End of Encryptfile
EnumCerts.sln
#include <windows.h>
#include <wincrypt.h>
#include <iostream>

#define CSP_NAME  "Longmai mToken GM3000 CSP V1.1"

using namespace std;

int main(int argc, char* argv[])
{
	HCRYPTPROV hCryptProv = NULL;

	cout << "Attempt to acquire context for CSP...";
	if(!CryptAcquireContext(
		&hCryptProv,
		NULL,
		CSP_NAME,
		PROV_RSA_FULL,
		CRYPT_VERIFYCONTEXT
	))
	{
		cout << endl << "Can't acquire context, Error code = 0x" << hex << GetLastError() << dec << endl;
		return -1;
	}
	else
		cout << "OK." << endl;

	HCERTSTORE hCertStore = NULL;

	cout << "Attempt to open the certificate storage...";
	hCertStore = CertOpenStore(
		CERT_STORE_PROV_SYSTEM,   // The store provider type.
		0,                        // The encoding type is not needed.
		hCryptProv,               // Use the epassNG HCRYPTPROV.
		CERT_SYSTEM_STORE_CURRENT_USER,
		L"MY"
		);
	if(NULL == hCertStore)
	{
		cout << endl << "Can't open certificates store. Error code = 0x" << hex << GetLastError() << dec << endl;
	}
	else
		cout << "OK." << endl;

	// Enum the certficates. pCertContext must be NULL at the first time.
	PCCERT_CONTEXT pCertContext = NULL;
	DWORD dwTotalCert = 0;

	while(pCertContext = CertEnumCertificatesInStore( hCertStore, pCertContext))
	{
		if(NULL == pCertContext)
			break;

//////////////////////////////////////////////////////////////////////////
// How to get the subject name, see below:
		// First we must get the length of the subject name.
		DWORD dwNameLen = 0;
		dwNameLen = CertGetNameString(
					pCertContext,
					CERT_NAME_SIMPLE_DISPLAY_TYPE,
					0, NULL, NULL, 0
		);
		if(0 == dwNameLen)
		{
			cout << "Can't get the subject name of the certificate." << endl;
			break;
		}

		// Now let's alloc memory for the subject name.
		char* pszTemp = NULL;
		pszTemp = new char[dwNameLen + 1];	// Plus 1 to hold the '\0'.
		if(NULL == pszTemp)
			break;
		ZeroMemory(pszTemp, dwNameLen + 1);

		// Second call to CertGetNameString() to get the subject name.
		if(CertGetNameString(
				pCertContext,
				CERT_NAME_SIMPLE_DISPLAY_TYPE,
				0,
				NULL,
				pszTemp,
				dwNameLen + 1))
		{
			cout << "Oh, the subject name is : " << pszTemp << endl;
		}

		// Free the memory allocated for the subject name.
		delete[] pszTemp;
		pszTemp = NULL;
		++dwTotalCert;

// Ok, we got the subject name.
//////////////////////////////////////////////////////////////////////////
	}

	if(0 == dwTotalCert)
	{
		cout << "No certficate find." << endl; 
	}

	// Close the store.
	if(CertCloseStore(hCertStore, 0))
	{
		cout << "Store closed. All information free." << endl;
	}
	else
	{
		cout << "Store closed. But some information in use." << endl;
	}
    getchar();
	return 0;
}
SKF,encryptData.sln
#include "../../include/skfapi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Win32Dlg.h"

#define	TRUE	1
#define FALSE	0
#define ERROR_THROW(r) {if((r) != SAR_OK) goto END_OF_FUN;}
#pragma comment(lib, "../../lib/mtoken_gm3000.lib")



void main()
{
	ULONG ulRslt = SAR_OK;
	HANDLE hdev = NULL;
	HANDLE happ = NULL;
	HANDLE hcont = NULL;
	HANDLE hkey = NULL;
	char	szDevName[256] = {0};
	char	szAppName[256] = {0};
	char	szContName[256] = {0};
	char	pUserPin[64] = {'0', '1', '2', '3', '4', '5', '6', '\0'};
	ULONG	ulDevNameLen = 256;
	ULONG	ulAppNameLen = 256;
	ULONG	ulContNameLen = 256;
	ULONG	ulRetryCount = 0;
	BYTE	pbData[2048] = {0};
	BYTE	pbEncryptedData[2048] = {0};
	BYTE	*pbEncrypted_ptr = pbEncryptedData;
	ULONG	ulEncryptedDataLen = 2048;
	ECCPUBLICKEYBLOB	ecc_pub = {0};
	PECCCIPHERBLOB		pecc_cipher = NULL;
	ULONG	ulEccpubLen = sizeof(ECCPUBLICKEYBLOB);
	BLOCKCIPHERPARAM bp = {0};

	

	ulRslt = SKF_EnumDev(TRUE, szDevName, &ulDevNameLen);
	ERROR_THROW(ulRslt)

	char *pdevname = szDevName;
	ulRslt = SKF_ConnectDev(pdevname, &hdev);
	ERROR_THROW(ulRslt)

	ulRslt = SKF_EnumApplication(hdev, szAppName, &ulAppNameLen);
	ERROR_THROW(ulRslt)

	char *pappname = szAppName;
	ulRslt = SKF_OpenApplication(hdev, pappname, &happ);
	ERROR_THROW(ulRslt)

	{
		CWin32Dlg dlg;

		if(dlg.RegisterClass())
		{
			return ;
		}

		if(dlg.CreateInstance())
		{
			return ;
		}

		while(dlg.ProcessNextMessage())
		{

		}
		memset(pUserPin, 0 , sizeof(pUserPin));
		strncpy(pUserPin, dlg.GetPin(), 64);
	}
	

	ulRslt = SKF_VerifyPIN(happ, USER_TYPE, pUserPin, &ulRetryCount);
	ERROR_THROW(ulRslt)

	ulRslt = SKF_EnumContainer(happ, szContName, &ulContNameLen);
	ERROR_THROW(ulRslt)

	char *pcontname = szContName;
	ulRslt = SKF_OpenContainer(happ, pcontname, &hcont);
	ERROR_THROW(ulRslt)

	//公钥从证书解析
	ulRslt = SKF_ExportPublicKey(hcont, FALSE, (BYTE *)&ecc_pub, &ulEccpubLen);
	ERROR_THROW(ulRslt)

	//此处需要保存Cipher,解密时需要导入
	pecc_cipher = (PECCCIPHERBLOB)malloc(sizeof(ECCCIPHERBLOB) + 64);
	memset(pecc_cipher, 0, sizeof(ECCCIPHERBLOB) + 64);
	ulRslt = SKF_ECCExportSessionKey(hcont, SGD_SM1_ECB, &ecc_pub, pecc_cipher, &hkey);
	ERROR_THROW(ulRslt)

	//根据加密模式设定IV
	memcpy(bp.IV, "12345678", 8);
	bp.IVLen = 8;
	bp.PaddingType = 1;

	ulRslt = SKF_LockDev(hdev, 0xFFFFFFFF);
	ERROR_THROW(ulRslt)

	ulRslt = SKF_EncryptInit(hkey, bp);
	if(ulRslt != SAR_OK)
	{
		SKF_UnlockDev(hdev);
		goto END_OF_FUN;
	}

	//分组计算时,SKF_EncryptUpdate每包数据长度为1024字节时,计算速度最快
	ulRslt = SKF_EncryptUpdate(hkey, pbData, 1024, pbEncrypted_ptr, &ulEncryptedDataLen);
	if(ulRslt != SAR_OK)
	{
		SKF_UnlockDev(hdev);
		goto END_OF_FUN;
	}

	pbEncrypted_ptr += ulEncryptedDataLen;
	ulEncryptedDataLen = 1024;
	ulRslt = SKF_EncryptFinal(hkey, pbEncrypted_ptr, &ulEncryptedDataLen);
	if(ulRslt != SAR_OK)
	{
		SKF_UnlockDev(hdev);
		goto END_OF_FUN;
	}

	ulRslt = SKF_UnlockDev(hdev);


END_OF_FUN:
	if(hkey != NULL)
		SKF_CloseHandle(hkey);
	if(hcont != NULL)
		SKF_CloseContainer(hcont);
	if(happ != NULL)
		SKF_CloseApplication(happ);
	if(hdev != NULL)
		SKF_DisConnectDev(hdev);	
	if(pecc_cipher != NULL)
	{
		free(pecc_cipher);
		pecc_cipher = NULL;
	}
	return ;

}
getusbinfos.sln
#include "stdafx.h"
#include "getinfos.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define PKCS_LIB_NAME			"gm3000_pkcs11.dll"

//Initialize the token Cryptoki library:
CGetInfos::CGetInfos():m_hDll(NULL_PTR)
{
	m_path = PKCS_LIB_NAME;
}

//Free the token Cryptoki library:Finish.
CGetInfos::~CGetInfos()
{
	//if load library failed ,but m_pToke is NULL, so call C_Finalize will be wrong
	if(m_pToken != NULL)
	{
		m_pToken->C_Finalize(NULL_PTR);
		m_pToken = NULL_PTR;
	}
	
	if(m_hDll)
	{
		FreeLibrary(m_hDll);
	}
}

unsigned long CGetInfos::GetSlotInfos(CK_SLOT_INFO_PTR pSlotInfo)
{
	CK_RV rv = CKR_OK;
	CK_ULONG ulCount = 0;
	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
	rv = m_pToken->C_GetSlotList(FALSE, NULL_PTR, &ulCount);
	if((rv != CKR_OK) || (ulCount <= 0))
		return CKR_DEVICE_ERROR;
	
	pSlotList = (CK_SLOT_ID_PTR)new CK_SLOT_ID [ulCount];
	if (pSlotList == NULL_PTR)
	{
		return CKR_HOST_MEMORY;
	}

	rv = m_pToken->C_GetSlotList(FALSE, pSlotList, &ulCount);
	if((rv != CKR_OK) || (ulCount <= 0))
	{
		delete [] pSlotList;
		pSlotList = NULL_PTR;
		return CKR_SLOT_ID_INVALID;
	}
	/*Get slot information for the first slot*/
	for (unsigned int i = 0; i < ulCount; ++i)
	{
		rv = m_pToken->C_GetSlotInfo(pSlotList[i], pSlotInfo);
		if(rv != CKR_OK)
		{
			delete [] pSlotList;
			pSlotList = NULL_PTR;
			return CKR_FUNCTION_FAILED;
		}
		//ShowSlotInfo(pSlotInfo);
	}

	delete [] pSlotList;
	pSlotList = NULL_PTR;
	return CKR_OK;
}

unsigned long CGetInfos::GetTokenInfos(CK_TOKEN_INFO_PTR pTokenInfo)
{
	CK_RV rv = CKR_OK;
	CK_ULONG ulCount = 0;
	CK_SLOT_ID_PTR pSlotList = NULL_PTR;

	rv = m_pToken->C_GetSlotList(TRUE, NULL_PTR, &ulCount);
	if((rv != CKR_OK) || (ulCount <= 0))
		return CKR_DEVICE_ERROR;
	pSlotList = (CK_SLOT_ID_PTR)new CK_SLOT_ID [ulCount];
	rv = m_pToken->C_GetSlotList(TRUE, pSlotList, &ulCount);
	if((rv != CKR_OK) || (ulCount <= 0))
	{
		delete [] pSlotList;
		pSlotList = NULL_PTR;
		return CKR_TOKEN_NOT_PRESENT;
	}
	/*Get slot information for the first token*/
	for (unsigned int i = 0; i < ulCount; ++i)
	{
		rv = m_pToken->C_GetTokenInfo(pSlotList[i], pTokenInfo);
		if(rv != CKR_OK)
		{
			delete [] pSlotList;
			pSlotList = NULL_PTR;
			return CKR_FUNCTION_FAILED;
		}
		//ShowTokenInfo(pTokenInfo);
	}
	delete [] pSlotList;
	pSlotList = NULL_PTR;
	return CKR_OK;
}

bool CGetInfos::CheckRV(const char* szInfo, unsigned long rv)
{
	printf(szInfo);
	if(CKR_OK == rv)
	{
		//printf(" ... OK.\n");
		return true;
	}

	printf(" ... FAILED. ");

	switch(rv)
	{
	case CKR_SLOT_ID_INVALID:
		printf("[CKR_SLOT_ID_INVALID]");
		break;
	case CKR_TOKEN_NOT_PRESENT:
		printf("[CKR_TOKEN_NOT_PRESENT]");
		break;
	case CKR_FUNCTION_FAILED:
		printf("[CKR_FUNCTION_FAILED]");
		break;
	case CKR_DEVICE_ERROR:
		printf("[CKR_DEVICE_ERROR]");
		break;
	case CKR_HOST_MEMORY:
		printf("[CKR_HOST_MEMORY]");
		break;
	default:
		printf("[Unknown ERROR: 0x%08X]", rv);
	}

	printf("\n");
	return false;
}

void CGetInfos::ShowSlotInfo(CK_SLOT_INFO_PTR slotinfo)
{
	printf("\nSlot information:\n");

	char DescBuffer[65] = {0};
	memcpy(DescBuffer,slotinfo->slotDescription,64);
	DescBuffer[64] = 0; 
	int i = 0;
	for(i = 63; i > 0; --i)
		if(' ' == DescBuffer[i])
			DescBuffer[i] = '\0';
		else
			break;

	printf("\tSlotDescription       = %s\n", DescBuffer);

	char manuBuffer[33] = {0};
	memcpy(manuBuffer,slotinfo->manufacturerID,32);
	manuBuffer[32] = 0; 
	for(i = 31; i > 0; --i)
		if(' ' == manuBuffer[i])
			manuBuffer[i] = '\0';
		else
			break;
	
	printf("\tManufacturerID        = %s\n", manuBuffer);
	printf("\tFlags                 = %08X\n", slotinfo->flags);
	printf("\tFirmwareVersion.major = %d\n", slotinfo->firmwareVersion.major);
	printf("\tFirmwareVersion.minor = %d\n", slotinfo->firmwareVersion.minor);
	printf("\tHardwareVersion.major = %d\n", slotinfo->hardwareVersion.major);
	printf("\tHardwareVersion.minor = %d\n\n", slotinfo->hardwareVersion.minor);

}

void CGetInfos::ShowTokenInfo(CK_TOKEN_INFO_PTR tokenInfo)
{
	printf("\nToken information:\n");
	char label[33] = {0};
	memcpy(label, tokenInfo->label, 32);
	printf("\tLabel                 = %s\n", label);

	char manuBuffer[33] = {0};
	memcpy(manuBuffer,tokenInfo->manufacturerID,32);
	manuBuffer[32] = 0; 
	printf("\tManufacturerID        = %s\n", manuBuffer);

	char modelBuffer[17] = {0};
	memcpy(modelBuffer,tokenInfo->model,16);
	manuBuffer[16] = 0; 
	printf("\tModel                 = %s\n", modelBuffer);

	char SNBuffer[17] = {0};
	memcpy(SNBuffer,tokenInfo->serialNumber,16);
	manuBuffer[16] = 0; 
	printf("\tSerialNumber          = %s\n", SNBuffer);

	printf("\tFlags                 = 0x%08X\n", tokenInfo->flags);
	printf("\tulMaxSessionCount     = %d\n", tokenInfo->ulMaxSessionCount);
	printf("\tulSessionCount        = %d\n", tokenInfo->ulSessionCount);
	printf("\tulMaxRwSessionCount   = %d\n",tokenInfo->ulMaxRwSessionCount);
	printf("\tulRwSessionCount      = %d\n",tokenInfo->ulRwSessionCount);
	printf("\tulMaxPinLen           = %d\n",tokenInfo->ulMaxPinLen);
	printf("\tulMinPinLen           = %d\n",tokenInfo->ulMinPinLen); 
	printf("\tulTotalPublicMemory   = %d\n", tokenInfo->ulTotalPublicMemory);
	printf("\tulTotalPrivateMemory  = %d\n", tokenInfo->ulTotalPrivateMemory);
	printf("\tulFreePublicMemory    = %d\n", tokenInfo->ulFreePublicMemory);
	printf("\tulFreePrivateMemory   = %d\n", tokenInfo->ulFreePrivateMemory);
	printf("\tHardwareVersion.major = %d\n", tokenInfo->hardwareVersion.major);
	printf("\tHardwareVersion.minor = %d\n", tokenInfo->hardwareVersion.minor);
	printf("\tFirmwareVersion.major = %d\n", tokenInfo->firmwareVersion.major);
	printf("\tFirmwareVersion.minor = %d\n", tokenInfo->firmwareVersion.minor);
	printf("\tToken utcTime         = %d\n", 0);

}

unsigned long CGetInfos::GetCryptokiInfos(CK_INFO_PTR pInfo)
{

	memset(pInfo, 0,  sizeof(pInfo));
	if(m_pToken->C_GetInfo(pInfo) != CKR_OK)
	{
		return CKR_FUNCTION_FAILED;
	}
	return CKR_OK;
}

void CGetInfos::ShowCryptokiInfos(CK_INFO_PTR pInfo)
{
	printf("\nCryptoki informations:\n");
	printf("\tCryptokiVersion.major = %d\n", pInfo->cryptokiVersion.major);
	printf("\tCryptokiVersion.minor = %d\n", pInfo->cryptokiVersion.minor);
	printf("\tLibraryVersion.major  = %d\n", pInfo->libraryVersion.major);
	printf("\tLibraryVersion.minor  = %d\n", pInfo->libraryVersion.minor);
	printf("\tFlags                 = 0x%08X\n", pInfo->flags);

	char LibDescBuffer[33] = {0};
	memcpy(LibDescBuffer,pInfo->libraryDescription,32);
	LibDescBuffer[32] = 0; 
	
	printf("\tLibraryDescription    = %s\n", LibDescBuffer);

	char manuBuffer[33] = {0};
	memcpy(manuBuffer,pInfo->manufacturerID,32);
	manuBuffer[32] = 0;

	printf("\tManufacturerID        = %s\n\n", manuBuffer);
}

bool CGetInfos::LoadLib()
{
#if defined(WIN32)
	m_hDll = LoadLibrary(m_path);
#else
	m_hDll = dlopen(m_path, RTLD_NOW);
#endif
	
	if(m_hDll == NULL_PTR)
	{
		printf("Load Library Error!");
		return false;
	}

	typedef CK_RV (* C_GETFUNCTIONLISTPROC)(CK_FUNCTION_LIST_PTR_PTR);
	C_GETFUNCTIONLISTPROC pC_GetFunctionList = (C_GETFUNCTIONLISTPROC)GetProcAddress(m_hDll,"C_GetFunctionList");
	if(pC_GetFunctionList == NULL_PTR)
	{
		printf("Get function list failed.\n");
		return false;
	}
	if(CKR_OK!=pC_GetFunctionList(&m_pToken))
	{
		printf("Get function list failed.\n");
		return false;
	}
	if(CKR_OK != m_pToken->C_Initialize(NULL_PTR))
	{
		printf("Call C_Initialize failed.\n");
		return false;
	}
	return true;
}
PKCStest.sln
#include "AESTest.h"
#include "common.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

AESTest::AESTest(char* dll_file_path):CBaseAll(dll_file_path)
{
	m_hKey = 0;
}

AESTest::~AESTest()
{

}


void AESTest::Test()
{
	if(CKR_OK != BaseAllStart())
		return;
	GenerateKey();
	if(m_hKey == 0)
	{
		BaseAllEnd();
		return ;
	}
	crypt_Single();
	crypt_Update();
	BaseAllEnd();
}
void AESTest::GenerateKey()
{
	do{
		SHOW_INFO("Generate Des key to test...");
		CK_OBJECT_CLASS oClass = CKO_SECRET_KEY;
		CK_KEY_TYPE keyType = CKK_AES; 
		CK_BBOOL bTrue = true;
		CK_BBOOL bFalse = false;
		CK_ULONG ulLen = 16;
		CK_MECHANISM mechanism = {CKM_AES_KEY_GEN, NULL_PTR, 0};
		CK_ATTRIBUTE Destem[] = {
			{CKA_CLASS, &oClass, sizeof(CK_OBJECT_CLASS)},
			{CKA_KEY_TYPE, &keyType, sizeof(CK_KEY_TYPE)},
			{CKA_TOKEN, &bFalse, sizeof(CK_BBOOL)},
			{CKA_PRIVATE, &bTrue, sizeof(CK_BBOOL)},
			{CKA_ENCRYPT, &bTrue, sizeof(CK_BBOOL)},
			{CKA_DECRYPT, &bTrue, sizeof(CK_BBOOL)},
			{CKA_VALUE_LEN, &ulLen, sizeof(CK_ULONG)}, 
		};
		CK_ULONG ulCount = 7;
		//generate key:
		START_OP("generate AES key...")
			CK_RV rv =  m_gToken->C_GenerateKey(hSession, &mechanism, Destem, ulCount, &m_hKey); 
		CHECK_OP(rv)
	}while(0);
}
void AESTest::crypt_Single()
{
	const CK_ULONG DATA_LENGTH = 1024*3;
	CK_BYTE bIn[DATA_LENGTH] = {0}, bTemp[DATA_LENGTH] = {0}, bOut[DATA_LENGTH] = {0};
	CK_ULONG ulIn = 0, ulOut = 0, ulTemp = 0;
	CK_ULONG Mechanism[3] = {CKM_AES_CBC, CKM_AES_ECB, CKM_AES_CBC_PAD};
	CK_BYTE_PTR bHint[3] = {(CK_BYTE_PTR)"CKM_AES_CBC: ",\
							(CK_BYTE_PTR)"CKM_AES_ECB: ",
							(CK_BYTE_PTR)"CKM_AES_CBC_PAD: "};
	SHOW_INFO("\nAES: C_Encrypt/C_Decrypt: \n");
	for(int i=0;i<3;i++)
	{
		ulIn = 1024;
		if(i==2)//pad
			ulIn = 1000;
		for(register CK_ULONG i0 = 0;i0<ulIn;i0++)
			bIn[i0] = (CK_BYTE)i0;
		
		
		SHOW_INFO("\n*	*	*	*	*	*	*	*	*	*	*	\n");
		SHOW_INFO(bHint[i]);
		//ecnrypt init:
		CK_BYTE iv[16] = {'*','2','1','0','4','z','y','b','*','2','1','0','4','z','y','b'};
		CK_MECHANISM ckMechanism = {Mechanism[i], iv, 16};
		START_OP("Encrypting initialize.")  
		CK_RV rv =  m_gToken->C_EncryptInit(hSession, &ckMechanism, m_hKey); 
		CHECK_OP(rv)

		START_OP("Encrypt the message.")
		//Get the encrypted buffer's size:
		//{{{Here, I do not invoke "C_Encrypt" twice for I had declared bTemp with a size=1024.
		//If you do not declare the result's buffer previous,
		//you should invoke twice to get the buffer's size, such as:[Decrypt is similar]
		rv =  m_gToken->C_Encrypt(hSession, bIn, ulIn, NULL, &ulTemp);
		//}}}
		CheckRV("C_Encrypt[get buffer's size]", rv);
		//encrypt:
		rv =  m_gToken->C_Encrypt(hSession, bIn, ulIn, bTemp, &ulTemp);
		CheckRV("C_Encrypt", rv);
		CHECK_OP(rv);
		SHOW_INFO("Data encrypted: \n");
		ShowData(bTemp, ulTemp);

		START_OP("Decrypting initialize.");
		rv =  m_gToken->C_DecryptInit(hSession, &ckMechanism, m_hKey);
		CHECK_OP(rv);
		START_OP("Decrypt the message.");
		//Get buffer's size:
		rv =  m_gToken->C_Decrypt(hSession, bTemp, ulTemp, NULL, &ulOut);
		//Get decrypted data:
		rv =  m_gToken->C_Decrypt(hSession, bTemp, ulTemp, bOut, &ulOut);
		CHECK_OP(rv);
		SHOW_INFO("Data decrypted: \n");
		ShowData(bOut, ulOut);
		
		START_OP("Compare the original message and decrypted data: ");
		if(0 == memcmp(bIn, bOut, ulOut))
		{
			CHECK_OP(CKR_OK);
		}
		else
		{
			SHOW_INFO("....[FAILED]\n");
		}
	}
}

void AESTest::crypt_Update()
{
	const CK_ULONG DATA_LENGTH = 1024*3;
	CK_BYTE bIn[DATA_LENGTH] = {0}, bTemp[DATA_LENGTH] = {0}, bOut[DATA_LENGTH] = {0};
	CK_ULONG ulIn = 0, ulOut = 0, ulTemp = 0;
	CK_ULONG Mechanism[3] = {CKM_AES_CBC, CKM_AES_ECB, CKM_AES_CBC_PAD};
	CK_BYTE_PTR bHint[3] = {(CK_BYTE_PTR)"CKM_AES_CBC: ",\
									(CK_BYTE_PTR)"CKM_AES_ECB: ",\
									(CK_BYTE_PTR)"CKM_AES_CBC_PAD: "};
	SHOW_INFO("\n*	*	*	*	*	*	*	*	*	*	*	*	*	*	*	*\n");
	for(int i=0;i<3;i++)
	{
		ulIn = 1024;
		if(i == 2)
		{//PAD
			ulIn = 1000;
		}
		for(register CK_ULONG i0 = 0;i0<ulIn;i0++)
			bIn[i0] = (CK_BYTE)i0;

		SHOW_INFO("\n");
		SHOW_INFO("\nAES: C_EncryptUpdate/C_DecryptUpdate: \n");
		SHOW_INFO(bHint[i]);
		//ecnrypt init:
		CK_BYTE iv[16] = {'*','2','1','0','4','z','y','b','*','2','1','0','4','z','y','b'};
		CK_MECHANISM ckMechanism = {Mechanism[i], iv, sizeof(iv)};
		START_OP("Encrypting initialize.")  
			CK_RV rv =  m_gToken->C_EncryptInit(hSession, &ckMechanism, m_hKey); 
		CHECK_OP(rv)
		
		CK_ULONG ulEncrypted = 0;
		START_OP("Encrypt the message.");
		//invoked twice:
		const CK_ULONG ulEnc1stPice = 33;
		rv =  m_gToken->C_EncryptUpdate(hSession, bIn, ulEnc1stPice, NULL, &ulTemp);//get buffer's size.
		rv =  m_gToken->C_EncryptUpdate(hSession, bIn, ulEnc1stPice, bTemp, &ulTemp);
		//}}}
		CheckRV("C_Encrypt[get buffer's size]", rv);
		ulEncrypted+=ulTemp;
		ulTemp = 0;
		//encrypt:
		//invoked twice:
		rv =  m_gToken->C_EncryptUpdate(hSession,  &(bIn[ulEnc1stPice]), ulIn-ulEnc1stPice, NULL, &ulTemp);//get buffer's size.
		rv =  m_gToken->C_EncryptUpdate(hSession, &(bIn[ulEnc1stPice]), ulIn-ulEnc1stPice, &(bTemp[ulEncrypted]), &ulTemp);
		CheckRV("C_Encrypt", rv);
		CHECK_OP(rv);
		ulEncrypted+=ulTemp;
		ulTemp = 0;
		START_OP("C_EncryptFinal...");
		rv = m_gToken->C_EncryptFinal(hSession, NULL, &ulTemp);//Get buffer's size:
		rv = m_gToken->C_EncryptFinal(hSession, &(bTemp[ulEncrypted]), &ulTemp);
		CHECK_OP(rv);
		ulEncrypted+=ulTemp;
		ulTemp = 0;
		SHOW_INFO("Data encrypted: \n");
		ShowData(bTemp, ulEncrypted);
		 
		START_OP("Decrypting initialize.");
		rv =  m_gToken->C_DecryptInit(hSession, &ckMechanism, m_hKey);
		CHECK_OP(rv);
		START_OP("Decrypt the message.");
		
		CK_ULONG ulDecrypt = 0;
		const CK_ULONG ulDec1stPice = 17;
		rv =  m_gToken->C_DecryptUpdate(hSession, bTemp, ulDec1stPice, NULL, &ulOut);//Get buffer's size
		rv =  m_gToken->C_DecryptUpdate(hSession, bTemp, ulDec1stPice, bOut, &ulOut);
		ulDecrypt +=ulOut;
		ulOut = 0;
		//Get decrypted data:
		rv =  m_gToken->C_DecryptUpdate(hSession, &(bTemp[ulDec1stPice]), ulEncrypted-ulDec1stPice, NULL, &ulOut);//Get buffer's size
		rv =  m_gToken->C_DecryptUpdate(hSession, &(bTemp[ulDec1stPice]), ulEncrypted-ulDec1stPice, &(bOut[ulDecrypt]), &ulOut);
		CHECK_OP(rv);
		ulDecrypt +=ulOut;
		ulOut = 0;
		START_OP("C_DecryptFinale...");
		rv = m_gToken->C_DecryptFinal(hSession, NULL, &ulOut);//Get buffer's size
		rv = m_gToken->C_DecryptFinal(hSession, &(bOut[ulDecrypt]), &ulOut);
		CHECK_OP(rv);
		ulDecrypt +=ulOut;
		
		SHOW_INFO("Data decrypted: \n");
		ShowData(bOut, ulDecrypt);
		
		START_OP("Compare the original message and decrypted data: ");
		if(0 == memcmp(bIn, bOut, ulDecrypt))
		{
			CHECK_OP(CKR_OK);
		}
		else
		{
			SHOW_INFO("....[FAILED]\n");
		}
	}
}

标签:CK,rv,代码,CKR,PTR,printf,NULL,链接
From: https://www.cnblogs.com/sjd-sr/p/18125617

相关文章

  • 码农必看:常见源代码混淆技术详解
    背景一、项目组代码部署存在的问题在项目组中,核心代码模块被部署于用户服务器上。然而,另一家公司获取了该服务器的root密码,这就存在着潜在的数据泄露和代码泄露的风险。传统的解决方法是通过配置环境变量来进行数据库加密处理,或者直接将jar包放到服务器上。然而,这些方法都有可能......
  • 蓝桥杯真题代码记录(最优清零方案
    目录1.题目:2.我的代码:小结:1.题目:给定一个长度为N的数列41,42,…,AN。现在小蓝想通过若干次操作将这个数列中每个数字清零。每次操作小蓝可以选择以下两种之一:1.选择一个大于0的整数,将它减去1;2.选择连续区个大于0的整数,将它们各减去1。小蓝最少经......
  • Linux下的硬链接和软链接
    前言在Linux文件系统中,一个文件被分成两个部分:元数据(metadata)与用户数据(userdata)。元数据为文件的附加属性,如索引节点(Inode)、文件大小、文件创建时间、文件所有者等。元数据中并不包含文件名,文件名仅仅是为了方便用户使用。Linux文件系统为每一个保存在磁盘分区中的文件(无论......
  • 简单的四则运算生成器代码
     以下是python代码importrandomdefa():num1=random.randint(1,100)num2=random.randint(1,100)operator=random.choice(['+','-','*','/'])#如果是除法操作,确保分母不为零ifoperator=='/'......
  • 肖恩带你看C语言·编译和链接
    来咯来咯,又见面咯,看看编译和链接的知识,了解一下就好,不必深究~~~运行环境运行环境是指运行编译后的C语言程序所需的硬件和软件环境。硬件环境:包括CPU、内存、硬盘等物理设备,这些设备提供了程序运行所需的硬件资源。软件环境:主要是指操作系统和相关的库文件。操作系统提供......
  • Python爬虫+如何查看一个网页的源代码
    方法1(火狐浏览器为例):方法2(火狐浏览器为例):......
  • PHP代码审计——Day7-Bells
    漏洞解析functiongetUser($id){global$config,$db;if(!is_resource($db)){$db=newMySQLi($config['dbhost'],$config['dbuser'],$config['dbpass'],$config[�......
  • js代码的函数及应用
    昨天学习了单击事件及其应用,现在我们接触js的函数。什么是函数?函数是可以重复执行的代码,需要通过函数名称来执行代码。 自定义一个函数function功能名称(){代码}例题:   圆的面积   varr=5;varpi=3.14functionc......
  • Day34代码随想录(1刷)贪心
    435.无重叠区间给定一个区间的集合 intervals ,其中 intervals[i]=[starti,endi] 。返回 需要移除区间的最小数量,使剩余区间互不重叠 。示例1:输入:intervals=[[1,2],[2,3],[3,4],[1,3]]输出:1解释:移除[1,3]后,剩下的区间没有重叠。示例2:输入:in......
  • visualstudio设置代码片段
    代码片段用于快捷健自动补全代码进入IDE——工具——代码片段管理器(Ctrl+k+b)——复制文件路径在winr命令窗口打开更改完后,重命名后放到文件夹,重新打开IDE新建快捷键记录:RE+tab:Console.ReadLine();  新建一个Console.WriteLine的代码片段<?xmlversion="1.0"encoding......