CryptEncrypt 和CryptDecrypt 的使用

/********************************************************************
	created:	2014/08/25
	created:	25:8:2014   15:24
	file ext:	cpp
	author:		Ben
	
	purpose:	简单的演示下windows API 的加解密函数的使用

	Remarks:
*********************************************************************/


#include "stdafx.h"
#include<windows.h>
#include <wincrypt.h>

#include<iostream>
using namespace std;

HCRYPTPROV	m_hCryptProv; 
HCRYPTKEY	m_hKey; 
HCRYPTHASH	m_hHash; 

#define KEYCONTAINER _T("BenTestKeyContainer")
#define KEYLENGTH  0x00800000


BOOL CreateCryptSession(LPTSTR tszPassword)
{
	//---------------------------------------------------------------
	// Get the handle to the default provider. 
	if (m_hCryptProv == NULL)
	{
		if(!CryptAcquireContext(
			&m_hCryptProv, 
			KEYCONTAINER, 
			MS_ENHANCED_PROV, 
			PROV_RSA_FULL, 
			0))
		{
			if (GetLastError() == NTE_BAD_KEYSET)
			{
				if(!CryptAcquireContext(
					&m_hCryptProv, 
					KEYCONTAINER, 
					MS_ENHANCED_PROV, 
					PROV_RSA_FULL, 
					CRYPT_NEWKEYSET))
				{
					return FALSE;
				}
			}
			else
			{
				return FALSE;
			}
		}
	}

	//-----------------------------------------------------------
	// Create a hash object. 
	if (m_hHash == NULL)
	{
		if(!CryptCreateHash(
			m_hCryptProv, 
			CALG_MD5, 
			0, 
			0, 
			&m_hHash))
		{
			return FALSE;
		}
	}

	//-----------------------------------------------------------
	// Hash in the password data. 
	if(m_hKey) 
	{
		CryptDestroyKey(m_hKey); 
		m_hKey = NULL;
	}
	if(!CryptHashData(
		m_hHash, 
		(BYTE *)tszPassword, 
		_tcslen(tszPassword) * sizeof(TCHAR), 
		0)) 
	{
		return FALSE;
	}

	//-----------------------------------------------------------
	// Derive a session key from the hash object. 
	if(!CryptDeriveKey(
		m_hCryptProv, 
		CALG_RC4, 
		m_hHash, 
		KEYLENGTH, 
		&m_hKey))
	{ 
		return FALSE;
	}

	return TRUE;
}


BOOL DestroyCryptSession()
{
	//--------------------------------------------------------------------
	// Destroy session key. 

	if(m_hKey) 
	{
		CryptDestroyKey(m_hKey); 
		m_hKey = NULL;
	}

	//--------------------------------------------------------------------
	// Destroy hash object. 
	if(m_hHash) 
	{
		CryptDestroyHash(m_hHash); 
		m_hHash = NULL;
	}

	//--------------------------------------------------------------------
	// Release provider handle. 

	if(m_hCryptProv) 
	{
		CryptReleaseContext(m_hCryptProv, 0); 
		m_hCryptProv = NULL;
	}

	return TRUE;
}


BOOL EncryptData(PBYTE pbBuffer, DWORD dwBufferLen, LPDWORD lpdwCount, BOOL bFinal=FALSE)
{
	if (m_hKey == NULL || pbBuffer == NULL || dwBufferLen == 0 || lpdwCount == NULL)
	{
		return FALSE;
	}

	//-----------------------------------------------------------
	// Encrypt data. 
	return CryptEncrypt(
		m_hKey, 
		NULL, 
		bFinal,
		0, 
		pbBuffer, 
		lpdwCount, 
		dwBufferLen);
}

// 解密数据
BOOL DecryptData(PBYTE pbBuffer, LPDWORD lpdwCount, BOOL bFinal=FALSE)
{
	if (m_hKey == NULL || pbBuffer == NULL || lpdwCount == NULL)
	{
		return FALSE;
	}

	//-----------------------------------------------------------
	// Decrypt the block of data. 
	if(!CryptDecrypt(
		m_hKey, 
		0, 
		bFinal, 
		0, 
		pbBuffer, 
		lpdwCount))
	{
		return FALSE;
	}

	return TRUE;
}


int _tmain(int argc, _TCHAR* argv[])
{
	int a = 1222;

	//-----------------------------------------------------------
	// 加密 数据 
	if (!CreateCryptSession(TEXT("c10509")))
	{
		cout << "CreateCryptSession Failed.. " << endl;

		return FALSE;
	}

	DWORD dwCount = sizeof(int);
	if (!EncryptData((PBYTE)&a, sizeof(int), &dwCount))
	{
		cout << "Encrypt Data Failed... " << endl;
	
		return FALSE;
	}
	else
	{
		cout << "Encrypt Data Successed... " << endl;
	}

	DestroyCryptSession();  // 注意这句的调用与前面 CreateCryptSession 成对
	//-----------------------------------------------------------


	{	// =======================================================
		// ====        解密部分  =============
		if (CreateCryptSession(TEXT("c10509")) == FALSE)
		{
			return FALSE;
		}

		// 解密
		//	DWORD dwDecryptCount = sizeof(decryptText);
		if (DecryptData((PBYTE)&a, &dwCount))
		{
			cout << "Decrypt Data Successed..." << endl;
		}
		else
		{
			cout << "DeCrypt Data Failed... " << endl;
		}

		DestroyCryptSession(); 
		// =======================================================
	}

	return 0;
}



可以参考的链接: http://blog.csdn.net/cnbragon/article/details/715058

MSDN:                        http://msdn.microsoft.com/zh-cn/aa382044



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Windows Crypto API 是一组用于数据加密和解密的功能和接口,它被广泛应用于 Windows 操作系统中的安全相关应用程序中。下面是一个简单的示例代码,演示如何使用 Windows Crypto API 进行数据加密和解密: ```c++ #include <iostream> #include <Windows.h> #include <Wincrypt.h> #pragma comment (lib, "Crypt32.lib") int main() { // 初始化 crypto API HCRYPTPROV hCryptProv; if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, 0)) { std::cerr << "CryptAcquireContext failed: " << GetLastError() << std::endl; return 1; } // 生成随机密钥 HCRYPTKEY hKey; if (!CryptGenKey(hCryptProv, CALG_AES_256, CRYPT_EXPORTABLE, &hKey)) { std::cerr << "CryptGenKey failed: " << GetLastError() << std::endl; CryptReleaseContext(hCryptProv, 0); return 1; } // 加密数据 const char* plainText = "Hello, world!"; DWORD plainTextLength = strlen(plainText) + 1; DWORD cipherTextLength = 0; if (!CryptEncrypt(hKey, NULL, TRUE, 0, NULL, &cipherTextLength, plainTextLength)) { std::cerr << "CryptEncrypt failed: " << GetLastError() << std::endl; CryptDestroyKey(hKey); CryptReleaseContext(hCryptProv, 0); return 1; } char* cipherText = new char[cipherTextLength]; memcpy(cipherText, plainText, plainTextLength); if (!CryptEncrypt(hKey, NULL, TRUE, 0, reinterpret_cast<BYTE*>(cipherText), &plainTextLength, cipherTextLength)) { std::cerr << "CryptEncrypt failed: " << GetLastError() << std::endl; CryptDestroyKey(hKey); CryptReleaseContext(hCryptProv, 0); delete[] cipherText; return 1; } // 解密数据 DWORD decryptedTextLength = 0; if (!CryptDecrypt(hKey, NULL, TRUE, 0, NULL, &decryptedTextLength)) { std::cerr << "CryptDecrypt failed: " << GetLastError() << std::endl; CryptDestroyKey(hKey); CryptReleaseContext(hCryptProv, 0); delete[] cipherText; return 1; } char* decryptedText = new char[decryptedTextLength]; memcpy(decryptedText, cipherText, cipherTextLength); if (!CryptDecrypt(hKey, NULL, TRUE, 0, reinterpret_cast<BYTE*>(decryptedText), &decryptedTextLength)) { std::cerr << "CryptDecrypt failed: " << GetLastError() << std::endl; CryptDestroyKey(hKey); CryptReleaseContext(hCryptProv, 0); delete[] cipherText; delete[] decryptedText; return 1; } std::cout << "Original text: " << plainText << std::endl; std::cout << "Encrypted text: " << cipherText << std::endl; std::cout << "Decrypted text: " << decryptedText << std::endl; // 清理 delete[] cipherText; delete[] decryptedText; CryptDestroyKey(hKey); CryptReleaseContext(hCryptProv, 0); return 0; } ``` 在上面的示例代码中,我们首先使用 `CryptAcquireContext` 函数初始化 crypto API,然后使用 `CryptGenKey` 函数生成一个随机密钥,接着使用 `CryptEncrypt` 函数对数据进行加密,最后使用 `CryptDecrypt` 函数对数据进行解密。请注意,这里使用的是 AES-256 对称加密算法,你可以根据需要选择其他加密算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值