⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crypto.cpp

📁 DSM Plugin.加密文件
💻 CPP
📖 第 1 页 / 共 2 页
字号:
		strcpy(szUserName, CTX);
		CreateContainer(szUserName);
	}

	PrintLog((DEST,"CryptAcquireContext |%d| |%s| |%s| |%d| |%d|",hProvider, szUserName, CSP_NAME, CSP_PROV, CONTEXT_FLAG));
    // Get handle for the default provider (use RSA encryption).
    if (! CryptAcquireContext(hProvider, szUserName, CSP_NAME, CSP_PROV, CONTEXT_FLAG)) {
		{
			PrintLog((DEST,"CryptAcquireContext failed...retrying."));
			PrintLog((DEST,"Using NULL Context flag."));
	PrintLog((DEST,"CryptAcquireContext |%d| |%s| |%s| |%d| |%d|",hProvider, szUserName, CSP_NAME, CSP_PROV, NULL_CONTEXT_FLAG));
			if (! CryptAcquireContext(hProvider, szUserName, CSP_NAME, CSP_PROV, NULL_CONTEXT_FLAG)) {
				PrintLog((DEST,"Unable to Acquire a Crypto context."));
				return -1;
			}

		}
    }

	return 0;

}

void CleanupCryptoKey(HCRYPTKEY hKey)
{

    CryptDestroyKey(hKey);

}

void CleanupCryptoContext(HCRYPTPROV hProvider)
{
    CryptReleaseContext(hProvider, 0);

}

int CreateDerivedCryptKey(HCRYPTPROV hProvider, HCRYPTKEY * hKey, char* password)
{

	HCRYPTHASH hHash = 0;
	DWORD dwLength;


	// Create a hash object.
	if(!CryptCreateHash(hProvider, CALG_MD5, 0, 0, &hHash)) {
	    PrintLog((DEST,"Error creating hash provider"));
        return -1;
	}

	// Hash the password string.
	dwLength = strlen(password);
	if(!CryptHashData(hHash, (BYTE *)password, dwLength, 0)) {
	    PrintLog((DEST,"Error hashing data"));
        return -1;
	}
 

	// Create a block cipher session key based on the hash of the password.
	if(!CryptDeriveKey(hProvider, CALG_RC4, hHash, CRYPT_EXPORTABLE, hKey)) {
	    PrintLog((DEST,"Error creating derived key"));
        return -1;
	}


	if(hHash != 0) CryptDestroyHash(hHash);

    return 0;

}



int ImportCryptKey(HCRYPTPROV hProvider, HCRYPTKEY * hKey, HANDLE hKeyFile)
				   
{
    const int      IN_BUFFER_SIZE    = 2048;
    const int      OUT_BUFFER_SIZE   = IN_BUFFER_SIZE + 64; // extra padding
    BYTE        pbBuffer[OUT_BUFFER_SIZE];
    DWORD       dwByteCount = 0, dwBytesWritten = 0;
	HCRYPTKEY	hExchangeKey;
	char		bitNess[8];

            PrintLog((DEST,"Reading KeyBlob"));
				//read in "bitness"

			if (! ReadFile(hKeyFile,bitNess,7,&dwBytesWritten,NULL)) {
                PrintLog((DEST,"Reading BLOB size failed"));
                return -1;
			}

			DebugLog((DEST,"Key bits is %s",bitNess));

            // Read in key blob size
            if (! ReadFile(hKeyFile,&dwByteCount,sizeof(dwByteCount),&dwBytesWritten,NULL)) {
                PrintLog((DEST,"Reading BLOB size failed"));
                return -1;
            }

			if (dwByteCount <= OUT_BUFFER_SIZE)
			{
				//read in the key blob itself from input file.
				if (! ReadFile(hKeyFile, pbBuffer, dwByteCount, &dwBytesWritten, NULL)) {
					PrintLog((DEST,"Reading BLOB failed"));
					return -1;
				}
			}
			else
			{
				PrintLog((DEST,"Possible buffer overrun"));
				return -1;
			}

    PrintLog((DEST,"Importing ExponentOfOne KeyBlob"));

	if( !CryptImportKey(hProvider, PrivateKeyWithExponentOfOne, sizeof(PrivateKeyWithExponentOfOne), 0, 0, &hExchangeKey))
	{
        PrintLog((DEST,"Import ExponentOfOne Key failed. (SetParams)"));
		return -1;
    }

    PrintLog((DEST,"Importing KEY KeyBlob"));
    //now, we convert the key blob back into a key (internally to the CSP), with the call to CryptImportKey.
    if (! CryptImportKey(hProvider, (const BYTE *)pbBuffer, dwByteCount, hExchangeKey, 0, hKey)) {
        PrintLog((DEST,"Error importing key."));
        return -1;
    }

	CleanupCryptoKey(hExchangeKey);

	return 0;
}


int GetKeyLen(HCRYPTKEY hKey)
{

	char		pKeyLN[20];
    BYTE		pbDataBuf[20];
	DWORD		pdwDataLen		  = 20;
	int keyLen = 0;

	//check the imported key's length
			CryptGetKeyParam(hKey, KP_KEYLEN, pbDataBuf, &pdwDataLen, 0);

			if (_snprintf(pKeyLN, sizeof(pKeyLN),"%2.2x",pbDataBuf[0]) < 0)
					PrintLog((DEST,"_snprintf failed - pKeyLN too small"));

			if (strcmp(pKeyLN,"80")==0)
			{
				keyLen = 128;
				PrintLog((DEST,"Imported Key is 128bit"));
			}
			if (strcmp(pKeyLN,"28")==0)
			{
				keyLen = 40;
				PrintLog((DEST,"Imported Key is 40bit"));
			}

			if (strcmp(pKeyLN,"38")==0)
			{
				keyLen = 56;
				PrintLog((DEST,"Imported Key is 56bit"));
			}

			return keyLen;
}


BOOL CreateContainer(char * container) 
{ 
	//--------------------------------------------------------------------
	// Verify and correct the Key Container and base keys if needed, otherwise, does nothing
	
	// Code from MSDN example
	
	HCRYPTPROV hCryptProv = 0;        // handle for the cryptographic provider context
	HCRYPTKEY hCKey;               // public/private key handle

    PrintLog((DEST,"CreateContainer %s", container));
	
	// CryptAcquireContext. Try to open the key container
	
	PrintLog((DEST,"CryptAcquireContext |%d| |%s| |%s| |%d| |%d|",hCryptProv, container, CSP_NAME, CSP_PROV, 0));
	if(CryptAcquireContext(
		&hCryptProv,               // handle to the CSP
		container,                  // container name 
		CSP_NAME,                      // use the default provider
		CSP_PROV,             // provider type
		0))                        // flag values
	{
		PrintLog((DEST,"A crypto context with the %s key container already exists.", szUserName));
	}
	else
	{ 
		//--------------------------------------------------------------------
		// Some sort of error occurred in acquiring the context.
		//probably didn't exist yet.
		// Create a new key container. 
		
	PrintLog((DEST,"CryptAcquireContext |%d| |%s| |%s| |%d| |%d|",hCryptProv, container, CSP_NAME, CSP_PROV, CRYPT_NEWKEYSET));
		if(CryptAcquireContext(
			&hCryptProv, 
			container, 
			CSP_NAME, 
			CSP_PROV, 
			CRYPT_NEWKEYSET)) 
		{
			PrintLog((DEST,"A new key container has been created."));
		}
		else
		{
			PrintLog((DEST,"Could not create a new key container."));
			return false;
		}
	} // end else

/*
	//--------------------------------------------------------------------
	// A cryptographic context with a key container is available. Get the
	// name of the key container. 
	if(CryptGetProvParam(
		hCryptProv,               // handle to the CSP
		PP_CONTAINER,             // get the key container name 
		(BYTE *)szUserName,       // pointer to the key container name
		&dwUserNameLen,           // length of name, preset to 100
		0)) 
	{
		PrintLog((DEST,"A crypto context has been acquired and the name on the key container is %s",szUserName));
	}
	else
	{
		// An error occurred while getting the key container name.
		PrintLog((DEST,"A context was acquired or created, but an error occurred getting the key container name."));
		return false;
	} 
*/
	
	//--------------------------------------------------------------------
	// A context with a key container is available.
	// Attempt to get the handle to the key exchange key. 
	
	if(CryptGetUserKey(
		hCryptProv,                     // handle to the CSP
		AT_SIGNATURE,                   // key specification
		&hCKey))                         // handle to the key
	{
		PrintLog((DEST,"A signature key is available."));
	}
	else
	{
		if(GetLastError() == NTE_NO_KEY) 
		{
			//----------------------------------------------------------------
			// The error was that there is a container but no key.
			
			// Create a signature key pair. 
			
			PrintLog((DEST,"The signature key does not exist."));
			PrintLog((DEST,"Create a signature key pair.")); 
			if(CryptGenKey(
				hCryptProv,
				AT_SIGNATURE,
				0,
				&hCKey)) 
			{
				PrintLog((DEST,"Created a signature key pair."));
			}
			else
			{
				PrintLog((DEST,"Error occurred creating a signature key.")); 
				return false;
			}
		}
		else
		{
        PrintLog((DEST,"An error other than NTE_NO_KEY getting signature key."));
		return false;
		}
	} // end if
	
	//PrintLog((DEST,"A signature key pair existed, or one was created."));
	
	// Destroy the signature key.
	
	if(hCKey)
	{
		if(!(CryptDestroyKey(hCKey)))
		{
			PrintLog((DEST,"Error during CryptDestroyKey"));
			return false;
		}
	} 
	
	// Next, check the exchange key. 
	if(CryptGetUserKey(
		hCryptProv,
		AT_KEYEXCHANGE,
		&hCKey)) 
	{
		PrintLog((DEST,"An exchange key exists. "));
	}
	else
	{
		// Check to determine whether an exchange key needs to be created.
		if(GetLastError()==NTE_NO_KEY) 
		{ 
			// Create a key exchange key pair.
			PrintLog((DEST,"The exchange key does not exist."));
			PrintLog((DEST,"Attempting to create an exchange key pair."));
			if(CryptGenKey(
				hCryptProv,
				AT_KEYEXCHANGE,
				0,
				&hCKey)) 
			{
				PrintLog((DEST,"Exchange key pair created."));
			}
			else
			{
				PrintLog((DEST,"Error occurred attempting to create an exchange key."));
				return false;
			}
		}
		else
		{
			PrintLog((DEST,"An error other than NTE_NO_KEY occurred."));
			return false;
		}
	}
	
	//PrintLog((DEST,"An exchange key pair existed, or one was created."));
	// Destroy the session key.
	
	if(hCKey)
	{
		if(!(CryptDestroyKey(hCKey)))
		{
			PrintLog((DEST,"Error during CryptDestroyKey"));
			return false;
		}
	}
	
	// Release the CSP.
	
	if(hCryptProv)
	{
		if(!(CryptReleaseContext(hCryptProv,0)))
		{
			PrintLog((DEST,"Error during CryptReleaseContext"));
			return false;
		}
	} 
	

	PrintLog((DEST,"Key Container is ready for use."));
	return true;

}



BOOL DeleteContainer(char * container) 
{ 
	//--------------------------------------------------------------------
	// Delete the Key Container (it will get re-created next time the plugin is used)
	

	HCRYPTPROV hCryptProv = 0;        // handle for the cryptographic provider context
	
    PrintLog((DEST,"DeleteContainer %s", container));
	
	// CryptAcquireContext. 
	
	PrintLog((DEST,"CryptAcquireContext |%d| |%s| |%s| |%d| |%d|",hCryptProv, container, CSP_NAME, CSP_PROV, CRYPT_DELETEKEYSET));
	  if(CryptAcquireContext(
		&hCryptProv,               // handle to the CSP
		container,                  // container name 
		CSP_NAME,                      // use the default provider
		CSP_PROV,             // provider type
		CRYPT_DELETEKEYSET))                        // flag values
	{
		PrintLog((DEST,"The %s key container has been deleted.", container));
	}
	else
	{ 
		//--------------------------------------------------------------------
		// Some sort of error occurred in acquiring the context. 
		PrintLog((DEST,"Could not delete container %s.", container));
		return false;
	} // end else

	return true;
}





⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -