C/C++ Crypto密碼庫調(diào)用的實現(xiàn)方法
Crypto 庫是C/C++的加密算法庫,這個加密庫很流行,基本上涵蓋了市面上的各類加密解密算法,以下代碼是我在學習是總結的,放到這里用于后期需要時能夠快速解決問題。
項目地址:https://www.cryptopp.com/
Sha256加密算法
Sha系列加密算法包括很多,基本上有以下幾種格式的加密方式,位數(shù)越大加密強度越大,此算法屬于單向加密算法與MD5類似但安全性高于MD5。
- SHA-1:生成摘要的性能比MD5略低
- SHA-256:可以生成長度256bit的信息摘要
- SHA-224:可以生成長度224bit的信息摘要
- SHA-384:可以生成長度384bit的信息摘要
- SHA-512:可以生成長度512bit的信息摘要
#include <iostream>
#include <Windows.h>
#include <string>
#include <sha.h>
#include <md5.h>
#include <crc.h>
#include <files.h>
#include <hex.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
// 計算文件的 SHA256 值
string CalSHA256_ByFile(char *pszFileName)
{
string value;
SHA256 sha256;
FileSource(pszFileName, true, new HashFilter(sha256, new HexEncoder(new StringSink(value))));
return value;
}
// 計算數(shù)據(jù)的 SHA256 值
string CalSHA256_ByMem(PBYTE pData, DWORD dwDataSize)
{
string value;
SHA256 sha256;
StringSource(pData, dwDataSize, true, new HashFilter(sha256, new HexEncoder(new StringSink(value))));
return value;
}
int main(int argc, char * argv[])
{
string src = "hello lyshark";
string dst;
// 單獨計算MD5值的使用
MD5 md5;
StringSource(src, true, new HashFilter(md5, new HexEncoder(new StringSink(dst))));
cout << "計算字符串MD5: " << dst << endl;
// 單獨計算CRC32值
CRC32 crc32;
StringSource(src, true, new HashFilter(crc32, new HexEncoder(new StringSink(dst))));
cout << "計算字符串CRC32: " << dst << endl;
// 計算一個數(shù)組
BYTE pArrayData[] = { 10, 20, 30, 40, 50 };
DWORD dwArraySize = sizeof(pArrayData);
dst.clear();
StringSource(pArrayData, dwArraySize, true, new HashFilter(md5, new HexEncoder(new StringSink(dst))));
cout << "計算數(shù)組的MD5: " << dst << endl;
// 直接對文件計算Sha256散列值
string sha = CalSHA256_ByFile("c://BuidIAT.exe");
cout << "文件散列值: " << sha << endl;
// 讀入文件到內(nèi)存后計算
HANDLE hFile = CreateFile(L"c://BuidIAT.exe", GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, NULL);
DWORD dwFileSize = GetFileSize(hFile, NULL);
BYTE *pData = new BYTE[dwFileSize];
ReadFile(hFile, pData, dwFileSize, NULL, NULL);
string sha2 = CalSHA256_ByMem(pData, dwFileSize);
cout << "內(nèi)存中文件散列值: " << sha2.c_str() << endl;
system("pause");
return 0;
}
AES 加密與解密
AES是對稱加密,AES可使用16,24或32字節(jié)密鑰(分別對應128,192和256位)。 Crypto++ 庫缺省的密鑰長度是16字節(jié),也就是 AES:: DEFAULT_KEYLENGTH。
對于 ECB 和 CBC 模式,處理的數(shù)據(jù)必須是塊大小的倍數(shù)?;蛘撸憧梢杂?StreamTransformationFilter 圍繞這個模式對象,并把它作為一個過濾器對象。StreamTransformationFilter 能夠緩存數(shù)據(jù)到塊中并根據(jù)需要填充。
#include<cryptlib.h>
#include<osrng.h>
#include<iostream>
#include<files.h>
#include<aes.h>
#include<modes.h>
#include<hex.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
int main(int argc, char * argv[])
{
cout << "Key 長度: " << AES::DEFAULT_KEYLENGTH << endl;
cout << "最小長度: " << AES::MIN_KEYLENGTH << endl;
cout << "最大長度: " << AES::MAX_KEYLENGTH << endl;
cout << "Block Size: " << AES::BLOCKSIZE << endl;
AutoSeededRandomPool rand;
// 產(chǎn)生一個隨機數(shù)的密鑰
SecByteBlock Key(0x00, AES::DEFAULT_KEYLENGTH);
rand.GenerateBlock(Key, Key.size());
// 產(chǎn)生一個隨機的初始向量
SecByteBlock ival(AES::BLOCKSIZE);
rand.GenerateBlock(ival, ival.size());
byte plainText[] = "hello lyshark";
size_t Textlen = std::strlen((char*)plainText) + 1;
cout << "待加密字符串長度: " << Textlen << endl;
// 加密字符串
CFB_Mode<AES>::Encryption cfbEncryption(Key, Key.size(), ival);
cfbEncryption.ProcessData(plainText, plainText, Textlen);
cout << "顯示加密后的十六進制數(shù): ";
StringSource strSource1(plainText, Textlen, true, new HexEncoder(new FileSink(cout)));
// 解密字符串 并將數(shù)據(jù)輸出到Cout流上
CFB_Mode<AES>::Decryption cfbDecryption(Key, Key.size(), ival);
cfbDecryption.ProcessData(plainText, plainText, Textlen);
cout << endl << "顯示解密后的十六進制數(shù): ";
StringSource strSource2(plainText, Textlen, true, new HexEncoder(new FileSink(cout)));
cout << endl;
system("pause");
return 0;
}
以下代碼使用CBC模式加密與解密指定字符串。如果需要針對字符串進行加解密則需要使用以下代碼實現(xiàn).
#include<cryptlib.h>
#include<osrng.h>
#include<iostream>
#include<files.h>
#include<aes.h>
#include<modes.h>
#include<hex.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
int main(int argc, char * argv[])
{
// 開辟空間并將空間賦予初始值0
byte key[CryptoPP::AES::DEFAULT_KEYLENGTH], iv[CryptoPP::AES::BLOCKSIZE];
memset(key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
memset(iv, 0x00, CryptoPP::AES::BLOCKSIZE);
// 指定需要加密的字符串與
std::string plaintext = "hello lyshark this is palintext";
std::string ciphertext;
std::string decryptedtext;
// 輸出加密前字符串長度
std::cout << "加密前字符串長度: " << plaintext.size() << " bytes" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
// 創(chuàng)建并開始加密字符串
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext));
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length());
stfEncryptor.MessageEnd();
// 輸出密文長度
std::cout << "加密密文長度: " << ciphertext.size() << " bytes" << std::endl;
for (int i = 0; i < ciphertext.size(); i++)
{
std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
// 解密被加密的字符串
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv);
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decryptedtext));
stfDecryptor.Put(reinterpret_cast<const unsigned char*>(ciphertext.c_str()), ciphertext.size());
stfDecryptor.MessageEnd();
// 輸出解密后的字符串長度
std::cout << "解密后的字符串: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
system("pause");
return 0;
}
下面的示例使用CFB模式實現(xiàn)快速對字符串進行加解密,該模式的數(shù)據(jù)的長度并不需要是AES的塊大小的倍數(shù).
#include<cryptlib.h>
#include<osrng.h>
#include<iostream>
#include<files.h>
#include<aes.h>
#include<modes.h>
#include<hex.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
int main(int argc, char * argv[])
{
AutoSeededRandomPool rand;
// 生成隨機Key
SecByteBlock key(0x00, AES::DEFAULT_KEYLENGTH);
rand.GenerateBlock(key, key.size());
// 生成隨機IV值
byte iv[AES::BLOCKSIZE];
rand.GenerateBlock(iv, AES::BLOCKSIZE);
// 需要加密的字符串
char plainText[] = "hello lyshark";
int messageLen = (int)strlen(plainText) + 1;
// 執(zhí)行快速加密
CFB_Mode<AES>::Encryption cfbEncryption(key, key.size(), iv);
cfbEncryption.ProcessData((byte*)plainText, (byte*)plainText, messageLen);
cout << "加密后的數(shù)據(jù): " << plainText << endl;
// 執(zhí)行快速解密
CFB_Mode<AES>::Decryption cfbDecryption(key, key.size(), iv);
cfbDecryption.ProcessData((byte*)plainText, (byte*)plainText, messageLen);
cout << "解密后的數(shù)據(jù): " << plainText << endl;
system("pause");
return 0;
}
AES2 加密:
#include<cryptlib.h>
#include<iostream>
#include <Windows.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
// AES加密
BOOL AesEncrypt(BYTE *pPassword, DWORD dwPasswordLength, BYTE *pData, DWORD &dwDataLength, DWORD dwBufferLength)
{
BOOL bRet = TRUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hCryptHash = NULL;
HCRYPTKEY hCryptKey = NULL;
do
{
// 獲取CSP句柄
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
if (FALSE == bRet)
break;
// 創(chuàng)建HASH對象
bRet = CryptCreateHash(hCryptProv, CALG_MD5, NULL, 0, &hCryptHash);
if (FALSE == bRet)
break;
// 對密鑰進行HASH計算
bRet = CryptHashData(hCryptHash, pPassword, dwPasswordLength, 0);
if (FALSE == bRet)
break;
// 使用HASH來生成密鑰
bRet = CryptDeriveKey(hCryptProv, CALG_AES_128, hCryptHash, CRYPT_EXPORTABLE, &hCryptKey);
if (FALSE == bRet)
break;
// 加密數(shù)據(jù)
bRet = CryptEncrypt(hCryptKey, NULL, TRUE, 0, pData, &dwDataLength, dwBufferLength);
if (FALSE == bRet)
break;
} while (FALSE);
// 關閉釋放
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptHash)
CryptDestroyHash(hCryptHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
// AES解密
BOOL AesDecrypt(BYTE *pPassword, DWORD dwPasswordLength, BYTE *pData, DWORD &dwDataLength, DWORD dwBufferLength)
{
BOOL bRet = TRUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hCryptHash = NULL;
HCRYPTKEY hCryptKey = NULL;
do
{
// 獲取CSP句柄
bRet = ::CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
if (FALSE == bRet)
break;
// 創(chuàng)建HASH對象
bRet = CryptCreateHash(hCryptProv, CALG_MD5, NULL, 0, &hCryptHash);
if (FALSE == bRet)
break;
// 對密鑰進行HASH計算
bRet = CryptHashData(hCryptHash, pPassword, dwPasswordLength, 0);
if (FALSE == bRet)
break;
// 使用HASH來生成密鑰
bRet = CryptDeriveKey(hCryptProv, CALG_AES_128, hCryptHash, CRYPT_EXPORTABLE, &hCryptKey);
if (FALSE == bRet)
break;
// 解密數(shù)據(jù)
bRet = CryptDecrypt(hCryptKey, NULL, TRUE, 0, pData, &dwDataLength);
if (FALSE == bRet)
break;
} while (FALSE);
// 關閉釋放
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptHash)
CryptDestroyHash(hCryptHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
int main(int argc, char * argv[])
{
BYTE pData[MAX_PATH] = { 0 };
DWORD dwDataLength = 0, dwBufferLength = MAX_PATH;
lstrcpy((char *)pData, "hello lyshark");
dwDataLength = 1 + lstrlen((char *)pData);
// 原始十六進制數(shù)據(jù)
printf("AES 原始數(shù)據(jù) [%d]: ", dwDataLength);
for (int i = 0; i < dwDataLength; i++)
{
printf("%02x ", pData[i]);
}
printf("\n\n");
// AES 加密
AesEncrypt((BYTE *)"AAAVCDERFGTYHUJI", 16, pData, dwDataLength, dwBufferLength);
printf("AES 加密后 [%d]: ", dwDataLength);
for (int i = 0; i < dwDataLength; i++)
{
printf("%02x ", pData[i]);
}
printf("\n\n");
// AES 解密
AesDecrypt((BYTE *)"AAAVCDERFGTYHUJI", 16, pData, dwDataLength, dwBufferLength);
printf("AES 解密后 [%d]: ", dwDataLength);
for (int i = 0; i < dwDataLength; i++)
{
printf("%02x ", pData[i]);
}
system("pause");
return 0;
}
Base64加解密:
#include<cryptlib.h>
#include<osrng.h>
#include<iostream>
#include <Windows.h>
#include<files.h>
#include<base64.h>
#include<modes.h>
#include<hex.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
void DisplayHex(BYTE *pData, DWORD dwSize)
{
for (int i = 0; i < dwSize; i++)
{
if ((0 != i) && (0 == i % 16))
printf("\n");
else if ((0 != i) && (0 == i % 8))
printf(" ");
printf("%02X ", pData[i]);
}
printf("\n");
}
int main(int argc, char * argv[])
{
unsigned char plainText[] = "hello lyshark";
// 對字符串編碼
string encoded;
Base64Encoder encoder;
encoder.Put(plainText, sizeof(plainText));
encoder.MessageEnd();
word64 size = encoder.MaxRetrievable();
if (size)
{
encoded.resize(size);
encoder.Get((byte *)&encoded[0], encoded.size());
}
cout << "編碼后的數(shù)據(jù): " << encoded << endl;
// 對字符串解碼
string decoded;
Base64Decoder decoder;
decoder.Put((byte *)encoded.data(), encoded.size());
decoder.MessageEnd();
size = decoder.MaxRetrievable();
if (size && size <= SIZE_MAX)
{
decoded.resize(size);
decoder.Get((byte *)&decoded[0], decoded.size());
}
cout << "對字符串解碼: " << decoded;
// 輸出解碼字符串的十六進制格式
char szOriginalData[] = "hello lyshark";
cout << "字符串十六進制格式: ";
DisplayHex((BYTE *)szOriginalData, (1 + lstrlen(szOriginalData)));
system("pause");
return 0;
}
Hash加密算法
使用hash算法計算特定文件的Hash值.
#include<cryptlib.h>
#include<iostream>
#include <Windows.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
BOOL GetFileData(char *pszFilePath, BYTE **ppFileData, DWORD *pdwFileDataLength)
{
BOOL bRet = TRUE;
BYTE *pFileData = NULL;
DWORD dwFileDataLength = 0;
HANDLE hFile = NULL;
DWORD dwTemp = 0;
do
{
hFile = CreateFile(pszFilePath, GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ |
FILE_SHARE_WRITE, NULL, OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
bRet = FALSE;
break;
}
dwFileDataLength = ::GetFileSize(hFile, NULL);
pFileData = new BYTE[dwFileDataLength];
if (NULL == pFileData)
{
bRet = FALSE;
break;
}
RtlZeroMemory(pFileData, dwFileDataLength);
ReadFile(hFile, pFileData, dwFileDataLength, &dwTemp, NULL);
// 返回
*ppFileData = pFileData;
*pdwFileDataLength = dwFileDataLength;
} while (FALSE);
if (hFile)
CloseHandle(hFile);
return bRet;
}
BOOL CalculateHash(BYTE *pData, DWORD dwDataLength, ALG_ID algHashType,
BYTE **ppHashData, DWORD *pdwHashDataLength)
{
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hCryptHash = NULL;
BYTE *pHashData = NULL;
DWORD dwHashDataLength = 0;
DWORD dwTemp = 0;
BOOL bRet = FALSE;
do
{
// 獲得指定CSP的密鑰容器的句柄
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
if (FALSE == bRet)
break;
// 創(chuàng)建一個HASH對象, 指定HASH算法
bRet = CryptCreateHash(hCryptProv, algHashType, NULL, NULL, &hCryptHash);
if (FALSE == bRet)
break;
// 計算HASH數(shù)據(jù)
bRet = ::CryptHashData(hCryptHash, pData, dwDataLength, 0);
if (FALSE == bRet)
break;
// 獲取HASH結果的大小
dwTemp = sizeof(dwHashDataLength);
bRet = ::CryptGetHashParam(hCryptHash, HP_HASHSIZE, (BYTE *)(&dwHashDataLength), &dwTemp, 0);
if (FALSE == bRet)
break;
// 申請內(nèi)存
pHashData = new BYTE[dwHashDataLength];
if (NULL == pHashData)
{
bRet = FALSE;
break;
}
RtlZeroMemory(pHashData, dwHashDataLength);
// 獲取HASH結果數(shù)據(jù)
bRet = CryptGetHashParam(hCryptHash, HP_HASHVAL, pHashData, &dwHashDataLength, 0);
if (FALSE == bRet)
break;
// 返回數(shù)據(jù)
*ppHashData = pHashData;
*pdwHashDataLength = dwHashDataLength;
} while (FALSE);
// 釋放關閉
if (FALSE == bRet)
{
if (pHashData)
{
delete[]pHashData;
pHashData = NULL;
}
}
if (hCryptHash)
CryptDestroyHash(hCryptHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
int main(int argc, char * argv[])
{
BYTE *pData = NULL;
DWORD dwDataLength = 0;
BYTE *pHashData = NULL;
DWORD dwHashDataLength = 0;
// 獲取文件流數(shù)據(jù)
GetFileData("c://BuidIAT.exe", &pData, &dwDataLength);
// 計算 MD5
CalculateHash(pData, dwDataLength, CALG_MD5, &pHashData, &dwHashDataLength);
printf("MD5 Hash -> ");
for (int i = 0; i < dwHashDataLength; i++)
printf("%x", pHashData[i]);
printf("\n\n", dwHashDataLength);
if (pHashData)
{
delete[]pHashData;
pHashData = NULL;
}
// 計算 SHA1
CalculateHash(pData, dwDataLength, CALG_SHA1, &pHashData, &dwHashDataLength);
printf("SHA1 -> ");
for (int i = 0; i < dwHashDataLength; i++)
printf("%x", pHashData[i]);
printf("\n\n", dwHashDataLength);
if (pHashData)
{
delete[]pHashData;
pHashData = NULL;
}
// 計算 SHA256
CalculateHash(pData, dwDataLength, CALG_SHA_256, &pHashData, &dwHashDataLength);
printf("SHA256 -> ");
for (int i = 0; i < dwHashDataLength; i++)
printf("%x", pHashData[i]);
printf("\n\n", dwHashDataLength);
if (pHashData)
{
delete[]pHashData;
pHashData = NULL;
}
system("pause");
return 0;
}
RSA加密算法
RSA算法包括公鑰與私鑰兩部,加密時會先使用RSA生成公鑰與私鑰,然后在進行加密.
#include<iostream>
#include <Windows.h>
using namespace std;
// 生成公鑰和私鑰
BOOL GenerateKey(BYTE **ppPublicKey, DWORD *pdwPublicKeyLength, BYTE **ppPrivateKey, DWORD *pdwPrivateKeyLength)
{
BOOL bRet = TRUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hCryptKey = NULL;
BYTE *pPublicKey = NULL;
DWORD dwPublicKeyLength = 0;
BYTE *pPrivateKey = NULL;
DWORD dwPrivateKeyLength = 0;
do
{
// 獲取CSP句柄
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
if (FALSE == bRet)
break;
// 生成公私密鑰對
bRet = CryptGenKey(hCryptProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hCryptKey);
if (FALSE == bRet)
break;
// 獲取公鑰密鑰的長度和內(nèi)容
bRet = CryptExportKey(hCryptKey, NULL, PUBLICKEYBLOB, 0, NULL, &dwPublicKeyLength);
if (FALSE == bRet)
break;
pPublicKey = new BYTE[dwPublicKeyLength];
RtlZeroMemory(pPublicKey, dwPublicKeyLength);
bRet = CryptExportKey(hCryptKey, NULL, PUBLICKEYBLOB, 0, pPublicKey, &dwPublicKeyLength);
if (FALSE == bRet)
break;
// 獲取私鑰密鑰的長度和內(nèi)容
bRet = CryptExportKey(hCryptKey, NULL, PRIVATEKEYBLOB, 0, NULL, &dwPrivateKeyLength);
if (FALSE == bRet)
break;
pPrivateKey = new BYTE[dwPrivateKeyLength];
RtlZeroMemory(pPrivateKey, dwPrivateKeyLength);
bRet = CryptExportKey(hCryptKey, NULL, PRIVATEKEYBLOB, 0, pPrivateKey, &dwPrivateKeyLength);
if (FALSE == bRet)
break;
// 返回數(shù)據(jù)
*ppPublicKey = pPublicKey;
*pdwPublicKeyLength = dwPublicKeyLength;
*ppPrivateKey = pPrivateKey;
*pdwPrivateKeyLength = dwPrivateKeyLength;
} while (FALSE);
// 釋放關閉
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
// 公鑰加密數(shù)據(jù)
BOOL RsaEncrypt(BYTE *pPublicKey, DWORD dwPublicKeyLength, BYTE *pData, DWORD &dwDataLength, DWORD dwBufferLength)
{
BOOL bRet = TRUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hCryptKey = NULL;
do
{
// 獲取CSP句柄
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
if (FALSE == bRet)
break;
// 導入公鑰
bRet = CryptImportKey(hCryptProv, pPublicKey, dwPublicKeyLength, NULL, 0, &hCryptKey);
if (FALSE == bRet)
break;
// 加密數(shù)據(jù)
bRet = CryptEncrypt(hCryptKey, NULL, TRUE, 0, pData, &dwDataLength, dwBufferLength);
if (FALSE == bRet)
break;
} while (FALSE);
// 釋放并關閉
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
// 私鑰解密數(shù)據(jù)
BOOL RsaDecrypt(BYTE *pPrivateKey, DWORD dwProvateKeyLength, BYTE *pData, DWORD &dwDataLength)
{
BOOL bRet = TRUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hCryptKey = NULL;
do
{
// 獲取CSP句柄
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
if (FALSE == bRet)
break;
// 導入私鑰
bRet = CryptImportKey(hCryptProv, pPrivateKey, dwProvateKeyLength, NULL, 0, &hCryptKey);
if (FALSE == bRet)
break;
// 解密數(shù)據(jù)
bRet = CryptDecrypt(hCryptKey, NULL, TRUE, 0, pData, &dwDataLength);
if (FALSE == bRet)
break;
} while (FALSE);
// 釋放并關閉
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return bRet;
}
int main(int argc, char * argv[])
{
BYTE *pPublicKey = NULL;
DWORD dwPublicKeyLength = 0;
BYTE *pPrivateKey = NULL;
DWORD dwPrivateKeyLength = 0;
BYTE *pData = NULL;
DWORD dwDataLength = 0;
DWORD dwBufferLength = 4096;
pData = new BYTE[dwBufferLength];
RtlZeroMemory(pData, dwBufferLength);
lstrcpy((char *)pData, "hello lyshark");
dwDataLength = 1 + lstrlen((char *)pData);
// 輸出加密前原始數(shù)據(jù)
printf("加密前原始數(shù)據(jù): ");
for (int i = 0; i < dwDataLength; i++)
printf("%x", pData[i]);
printf("\n\n");
// 生成公鑰和私鑰
GenerateKey(&pPublicKey, &dwPublicKeyLength, &pPrivateKey, &dwPrivateKeyLength);
printf("公鑰: ");
for (int i = 0; i < dwPublicKeyLength; i++)
printf("%.2x", pPublicKey[i]);
printf("\n\n");
printf("私鑰: ");
for (int i = 0; i < dwPrivateKeyLength; i++)
printf("%.2x", pPrivateKey[i]);
printf("\n\n");
// 使用公鑰加密
RsaEncrypt(pPublicKey, dwPublicKeyLength, pData, dwDataLength, dwBufferLength);
printf("公鑰加密: ");
for (int i = 0; i < dwDataLength; i++)
printf("%x", pData[i]);
printf("\n\n");
// 使用私鑰解密
RsaDecrypt(pPrivateKey, dwPrivateKeyLength, pData, dwDataLength);
printf("私鑰解密: ");
for (int i = 0; i < dwDataLength; i++)
printf("%x", pData[i]);
printf("\n\n");
delete[]pData;
delete[]pPrivateKey;
delete[]pPublicKey;
system("pause");
return 0;
}
Crypt庫實現(xiàn)RSA加密
RSA加密一般使用公鑰加密私鑰解密,先生成公鑰與私鑰,然后使用這兩份密鑰對字符串等數(shù)據(jù)進行操作.
#include<cryptlib.h>
#include<osrng.h>
#include<iostream>
#include<files.h>
#include <Windows.h>
#include <rsa.h>
#include <hex.h>
#include<modes.h>
#pragma comment(lib, "cryptlib.lib")
using namespace std;
using namespace CryptoPP;
// 定義全局隨機數(shù)池
RandomPool & GlobalRNG();
RandomPool & GlobalRNG()
{
static RandomPool randomPool;
return randomPool;
}
// 生成RSA密鑰對
BOOL GenerateRSAKey(DWORD dwRSAKeyLength, char *pszPrivateKeyFileName, char *pszPublicKeyFileName, BYTE *pSeed, DWORD dwSeedLength)
{
RandomPool randPool;
randPool.Put(pSeed, dwSeedLength);
// 生成RSA私鑰
RSAES_OAEP_SHA_Decryptor priv(randPool, dwRSAKeyLength);
HexEncoder privFile(new FileSink(pszPrivateKeyFileName)); // 打開文件實行序列化操作
priv.DEREncode(privFile);
privFile.MessageEnd();
// 生成RSA公鑰
RSAES_OAEP_SHA_Encryptor pub(priv);
HexEncoder pubFile(new FileSink(pszPublicKeyFileName)); // 打開文件實行序列化操作
pub.DEREncode(pubFile); // 寫密碼對象pub到文件對象pubFile里
pubFile.MessageEnd();
return TRUE;
}
/* 此處的加密算法是通過文件中的公鑰與私鑰進行加密的*/
// RSA加密字符串
string RSA_Encrypt_ByFile(char *pszOriginaString, char *pszPublicKeyFileName, BYTE *pSeed, DWORD dwSeedLength)
{
RandomPool randPool;
randPool.Put(pSeed, dwSeedLength);
FileSource pubFile(pszPublicKeyFileName, TRUE, new HexDecoder);
RSAES_OAEP_SHA_Encryptor pub(pubFile);
// 加密
string strEncryptString;
StringSource(pszOriginaString, TRUE, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(strEncryptString))));
return strEncryptString;
}
// RSA解密字符串
string RSA_Decrypt_ByFile(char *pszEncryptString, char *pszPrivateKeyFileName)
{
FileSource privFile(pszPrivateKeyFileName, TRUE, new HexDecoder);
RSAES_OAEP_SHA_Decryptor priv(privFile);
string strDecryptString;
StringSource(pszEncryptString, TRUE, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(strDecryptString))));
return strDecryptString;
}
/* 通過在內(nèi)存中的密鑰對進行加密與解密 */
// RSA加密字符串
string RSA_Encrypt_ByMem(char *pszOriginaString, char *pszMemPublicKey, BYTE *pSeed, DWORD dwSeedLength)
{
RandomPool randPool;
randPool.Put(pSeed, dwSeedLength);
StringSource pubStr(pszMemPublicKey, TRUE, new HexDecoder);
RSAES_OAEP_SHA_Encryptor pub(pubStr);
// 加密
string strEncryptString;
StringSource(pszOriginaString, TRUE, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(strEncryptString))));
return strEncryptString;
}
// RSA解密字符串
string RSA_Decrypt_ByMem(char *pszEncryptString, char *pszMemPrivateKey)
{
StringSource privStr(pszMemPrivateKey, TRUE, new HexDecoder);
RSAES_OAEP_SHA_Decryptor priv(privStr);
string strDecryptString;
StringSource(pszEncryptString, TRUE, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(strDecryptString))));
return strDecryptString;
}
int main(int argc, char * argv[])
{
// 指定公鑰與私鑰所在文件目錄
char szPrivateFile[] = "c://private.key";
char szPublicFile[] = "c://public.key";
// 指定一串隨機數(shù)種子
char szSeed[] = "ABCDESGHETYSQDGH";
// 以下就是待加密的字符串
char szOriginalString[] = "hello lyshark";
/* 此處是從文件中讀取出公鑰與私鑰對特定字符串進行加密與解密 */
// 生成RSA公私密鑰對
GenerateRSAKey(1024, szPrivateFile, szPublicFile, (BYTE *)szSeed, lstrlen(szSeed));
// RSA公鑰加密字符串
string strEncryptString = RSA_Encrypt_ByFile(szOriginalString, szPublicFile, (BYTE *)szSeed, lstrlen(szSeed));
// RSA私鑰解密字符串
string strDecryptString = RSA_Decrypt_ByFile((char *)strEncryptString.c_str(), szPrivateFile);
// 顯示
printf("原文字符串:\t[%d]%s\n", lstrlen(szOriginalString), szOriginalString);
printf("密文字符串:\t[%d]%s\n", strEncryptString.length(), strEncryptString.c_str());
printf("明文字符串:\t[%d]%s\n", strDecryptString.length(), strDecryptString.c_str());
printf("\n\n");
// --------------------------------------------------------------------------------------------------------------
/* 此處是在內(nèi)存中對指定字符串進行解密*/
char g_szPubKey[] = "填充公鑰";
char g_szPrivKey[] = "填充私鑰";
// RSA公鑰加密字符串
string strEncryptString_Mem = RSA_Encrypt_ByMem(szOriginalString, g_szPubKey, (BYTE *)szSeed, ::lstrlen(szSeed));
// RSA私鑰解密字符串
string strDecryptString_Mem = RSA_Decrypt_ByMem((char *)strEncryptString_Mem.c_str(), g_szPrivKey);
// 顯示
printf("原文字符串:\n[%d]%s\n", ::lstrlen(szOriginalString), szOriginalString);
printf("密文字符串:\n[%d]%s\n", strEncryptString_Mem.length(), strEncryptString_Mem.c_str());
printf("明文字符串:\n[%d]%s\n", strDecryptString_Mem.length(), strDecryptString_Mem.c_str());
system("pause");
return 0;
到此這篇關于C/C++ Crypto密碼庫調(diào)用的實現(xiàn)方法的文章就介紹到這了,更多相關C++ Crypto密碼庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C/C++?Qt?StringListModel?字符串列表映射組件詳解
StringListModel?字符串列表映射組件,該組件用于處理字符串與列表框組件中數(shù)據(jù)的轉(zhuǎn)換,通常該組件會配合ListView組件一起使用,本文給大家介紹了C/C++?Qt?StringListModel?字符串列表映射組件的相關知識,感興趣的朋友跟隨小編一起看看吧2021-12-12
error LNK2019: 無法解析的外部符號 問題的解決辦法
error LNK2019: 無法解析的外部符號 問題的解決辦法,需要的朋友可以參考一下2013-05-05
C語言調(diào)用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查
SQLite是一種輕量級的關系型數(shù)據(jù)庫管理系統(tǒng),是一個開源的、零配置的、服務器端的、自包含的、零管理的、事務性的SQL數(shù)據(jù)庫引擎,本文主要介紹了如何調(diào)用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查,需要的可以參考一下2023-08-08

