您好,登錄后才能下訂單哦!
這篇文章主要介紹“C/C++ Crypto密碼庫(kù)如何調(diào)用”,在日常操作中,相信很多人在C/C++ Crypto密碼庫(kù)如何調(diào)用問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C/C++ Crypto密碼庫(kù)如何調(diào)用”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
Sha系列加密算法包括很多,基本上有以下幾種格式的加密方式,位數(shù)越大加密強(qiáng)度越大,此算法屬于單向加密算法與MD5類似但安全性高于MD5。
SHA-1:生成摘要的性能比MD5略低
SHA-256:可以生成長(zhǎng)度256bit的信息摘要
SHA-224:可以生成長(zhǎng)度224bit的信息摘要
SHA-384:可以生成長(zhǎng)度384bit的信息摘要
SHA-512:可以生成長(zhǎng)度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; // 計(jì)算文件的 SHA256 值 string CalSHA256_ByFile(char *pszFileName) { string value; SHA256 sha256; FileSource(pszFileName, true, new HashFilter(sha256, new HexEncoder(new StringSink(value)))); return value; } // 計(jì)算數(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; // 單獨(dú)計(jì)算MD5值的使用 MD5 md5; StringSource(src, true, new HashFilter(md5, new HexEncoder(new StringSink(dst)))); cout << "計(jì)算字符串MD5: " << dst << endl; // 單獨(dú)計(jì)算CRC32值 CRC32 crc32; StringSource(src, true, new HashFilter(crc32, new HexEncoder(new StringSink(dst)))); cout << "計(jì)算字符串CRC32: " << dst << endl; // 計(jì)算一個(gè)數(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 << "計(jì)算數(shù)組的MD5: " << dst << endl; // 直接對(duì)文件計(jì)算Sha256散列值 string sha = CalSHA256_ByFile("c://BuidIAT.exe"); cout << "文件散列值: " << sha << endl; // 讀入文件到內(nèi)存后計(jì)算 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是對(duì)稱加密,AES可使用16,24或32字節(jié)密鑰(分別對(duì)應(yīng)128,192和256位)。 Crypto++ 庫(kù)缺省的密鑰長(zhǎng)度是16字節(jié),也就是 AES:: DEFAULT_KEYLENGTH。
對(duì)于 ECB 和 CBC 模式,處理的數(shù)據(jù)必須是塊大小的倍數(shù)?;蛘撸憧梢杂?StreamTransformationFilter 圍繞這個(gè)模式對(duì)象,并把它作為一個(gè)過濾器對(duì)象。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 長(zhǎng)度: " << AES::DEFAULT_KEYLENGTH << endl; cout << "最小長(zhǎng)度: " << AES::MIN_KEYLENGTH << endl; cout << "最大長(zhǎng)度: " << AES::MAX_KEYLENGTH << endl; cout << "Block Size: " << AES::BLOCKSIZE << endl; AutoSeededRandomPool rand; // 產(chǎn)生一個(gè)隨機(jī)數(shù)的密鑰 SecByteBlock Key(0x00, AES::DEFAULT_KEYLENGTH); rand.GenerateBlock(Key, Key.size()); // 產(chǎn)生一個(gè)隨機(jī)的初始向量 SecByteBlock ival(AES::BLOCKSIZE); rand.GenerateBlock(ival, ival.size()); byte plainText[] = "hello lyshark"; size_t Textlen = std::strlen((char*)plainText) + 1; cout << "待加密字符串長(zhǎng)度: " << Textlen << endl; // 加密字符串 CFB_Mode<AES>::Encryption cfbEncryption(Key, Key.size(), ival); cfbEncryption.ProcessData(plainText, plainText, Textlen); cout << "顯示加密后的十六進(jìn)制數(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 << "顯示解密后的十六進(jìn)制數(shù): "; StringSource strSource2(plainText, Textlen, true, new HexEncoder(new FileSink(cout))); cout << endl; system("pause"); return 0; }
以下代碼使用CBC模式加密與解密指定字符串。如果需要針對(duì)字符串進(jìn)行加解密則需要使用以下代碼實(shí)現(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; // 輸出加密前字符串長(zhǎng)度 std::cout << "加密前字符串長(zhǎng)度: " << 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(); // 輸出密文長(zhǎng)度 std::cout << "加密密文長(zhǎng)度: " << 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(); // 輸出解密后的字符串長(zhǎng)度 std::cout << "解密后的字符串: " << std::endl; std::cout << decryptedtext; std::cout << std::endl << std::endl; system("pause"); return 0; }
下面的示例使用CFB模式實(shí)現(xiàn)快速對(duì)字符串進(jìn)行加解密,該模式的數(shù)據(jù)的長(zhǎng)度并不需要是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; // 生成隨機(jī)Key SecByteBlock key(0x00, AES::DEFAULT_KEYLENGTH); rand.GenerateBlock(key, key.size()); // 生成隨機(jī)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; }
#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對(duì)象 bRet = CryptCreateHash(hCryptProv, CALG_MD5, NULL, 0, &hCryptHash); if (FALSE == bRet) break; // 對(duì)密鑰進(jìn)行HASH計(jì)算 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); // 關(guān)閉釋放 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對(duì)象 bRet = CryptCreateHash(hCryptProv, CALG_MD5, NULL, 0, &hCryptHash); if (FALSE == bRet) break; // 對(duì)密鑰進(jìn)行HASH計(jì)算 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); // 關(guān)閉釋放 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); // 原始十六進(jìn)制數(shù)據(jù) printf("AES 原始數(shù)據(jù) [%d]: ", dwDataLength); for (int i = 0; i < dwDataLength; i++) { printf("%02x ", pData[i]); } printf(" "); // AES 加密 AesEncrypt((BYTE *)"AAAVCDERFGTYHUJI", 16, pData, dwDataLength, dwBufferLength); printf("AES 加密后 [%d]: ", dwDataLength); for (int i = 0; i < dwDataLength; i++) { printf("%02x ", pData[i]); } printf(" "); // 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; }
#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(" "); else if ((0 != i) && (0 == i % 8)) printf(" "); printf("%02X ", pData[i]); } printf(" "); } int main(int argc, char * argv[]) { unsigned char plainText[] = "hello lyshark"; // 對(duì)字符串編碼 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; // 對(duì)字符串解碼 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 << "對(duì)字符串解碼: " << decoded; // 輸出解碼字符串的十六進(jìn)制格式 char szOriginalData[] = "hello lyshark"; cout << "字符串十六進(jìn)制格式: "; DisplayHex((BYTE *)szOriginalData, (1 + lstrlen(szOriginalData))); system("pause"); return 0; }
使用hash算法計(jì)算特定文件的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)建一個(gè)HASH對(duì)象, 指定HASH算法 bRet = CryptCreateHash(hCryptProv, algHashType, NULL, NULL, &hCryptHash); if (FALSE == bRet) break; // 計(jì)算HASH數(shù)據(jù) bRet = ::CryptHashData(hCryptHash, pData, dwDataLength, 0); if (FALSE == bRet) break; // 獲取HASH結(jié)果的大小 dwTemp = sizeof(dwHashDataLength); bRet = ::CryptGetHashParam(hCryptHash, HP_HASHSIZE, (BYTE *)(&dwHashDataLength), &dwTemp, 0); if (FALSE == bRet) break; // 申請(qǐng)內(nèi)存 pHashData = new BYTE[dwHashDataLength]; if (NULL == pHashData) { bRet = FALSE; break; } RtlZeroMemory(pHashData, dwHashDataLength); // 獲取HASH結(jié)果數(shù)據(jù) bRet = CryptGetHashParam(hCryptHash, HP_HASHVAL, pHashData, &dwHashDataLength, 0); if (FALSE == bRet) break; // 返回?cái)?shù)據(jù) *ppHashData = pHashData; *pdwHashDataLength = dwHashDataLength; } while (FALSE); // 釋放關(guān)閉 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); // 計(jì)算 MD5 CalculateHash(pData, dwDataLength, CALG_MD5, &pHashData, &dwHashDataLength); printf("MD5 Hash -> "); for (int i = 0; i < dwHashDataLength; i++) printf("%x", pHashData[i]); printf(" ", dwHashDataLength); if (pHashData) { delete[]pHashData; pHashData = NULL; } // 計(jì)算 SHA1 CalculateHash(pData, dwDataLength, CALG_SHA1, &pHashData, &dwHashDataLength); printf("SHA1 -> "); for (int i = 0; i < dwHashDataLength; i++) printf("%x", pHashData[i]); printf(" ", dwHashDataLength); if (pHashData) { delete[]pHashData; pHashData = NULL; } // 計(jì)算 SHA256 CalculateHash(pData, dwDataLength, CALG_SHA_256, &pHashData, &dwHashDataLength); printf("SHA256 -> "); for (int i = 0; i < dwHashDataLength; i++) printf("%x", pHashData[i]); printf(" ", dwHashDataLength); if (pHashData) { delete[]pHashData; pHashData = NULL; } system("pause"); return 0; }
RSA算法包括公鑰與私鑰兩部,加密時(shí)會(huì)先使用RSA生成公鑰與私鑰,然后在進(jìn)行加密.
#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; // 生成公私密鑰對(duì) bRet = CryptGenKey(hCryptProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hCryptKey); if (FALSE == bRet) break; // 獲取公鑰密鑰的長(zhǎng)度和內(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; // 獲取私鑰密鑰的長(zhǎng)度和內(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; // 返回?cái)?shù)據(jù) *ppPublicKey = pPublicKey; *pdwPublicKeyLength = dwPublicKeyLength; *ppPrivateKey = pPrivateKey; *pdwPrivateKeyLength = dwPrivateKeyLength; } while (FALSE); // 釋放關(guān)閉 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; // 導(dǎo)入公鑰 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); // 釋放并關(guān)閉 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; // 導(dǎo)入私鑰 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); // 釋放并關(guān)閉 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(" "); // 生成公鑰和私鑰 GenerateKey(&pPublicKey, &dwPublicKeyLength, &pPrivateKey, &dwPrivateKeyLength); printf("公鑰: "); for (int i = 0; i < dwPublicKeyLength; i++) printf("%.2x", pPublicKey[i]); printf(" "); printf("私鑰: "); for (int i = 0; i < dwPrivateKeyLength; i++) printf("%.2x", pPrivateKey[i]); printf(" "); // 使用公鑰加密 RsaEncrypt(pPublicKey, dwPublicKeyLength, pData, dwDataLength, dwBufferLength); printf("公鑰加密: "); for (int i = 0; i < dwDataLength; i++) printf("%x", pData[i]); printf(" "); // 使用私鑰解密 RsaDecrypt(pPrivateKey, dwPrivateKeyLength, pData, dwDataLength); printf("私鑰解密: "); for (int i = 0; i < dwDataLength; i++) printf("%x", pData[i]); printf(" "); delete[]pData; delete[]pPrivateKey; delete[]pPublicKey; system("pause"); return 0; }
RSA加密一般使用公鑰加密私鑰解密,先生成公鑰與私鑰,然后使用這兩份密鑰對(duì)字符串等數(shù)據(jù)進(jìn)行操作.
#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; // 定義全局隨機(jī)數(shù)池 RandomPool & GlobalRNG(); RandomPool & GlobalRNG() { static RandomPool randomPool; return randomPool; } // 生成RSA密鑰對(duì) 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)); // 打開文件實(shí)行序列化操作 priv.DEREncode(privFile); privFile.MessageEnd(); // 生成RSA公鑰 RSAES_OAEP_SHA_Encryptor pub(priv); HexEncoder pubFile(new FileSink(pszPublicKeyFileName)); // 打開文件實(shí)行序列化操作 pub.DEREncode(pubFile); // 寫密碼對(duì)象pub到文件對(duì)象pubFile里 pubFile.MessageEnd(); return TRUE; } /* 此處的加密算法是通過文件中的公鑰與私鑰進(jìn)行加密的*/ // 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)存中的密鑰對(duì)進(jìn)行加密與解密 */ // 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"; // 指定一串隨機(jī)數(shù)種子 char szSeed[] = "ABCDESGHETYSQDGH"; // 以下就是待加密的字符串 char szOriginalString[] = "hello lyshark"; /* 此處是從文件中讀取出公鑰與私鑰對(duì)特定字符串進(jìn)行加密與解密 */ // 生成RSA公私密鑰對(duì) 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("原文字符串: [%d]%s ", lstrlen(szOriginalString), szOriginalString); printf("密文字符串: [%d]%s ", strEncryptString.length(), strEncryptString.c_str()); printf("明文字符串: [%d]%s ", strDecryptString.length(), strDecryptString.c_str()); printf(" "); // -------------------------------------------------------------------------------------------------------------- /* 此處是在內(nèi)存中對(duì)指定字符串進(jìn)行解密*/ 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("原文字符串: [%d]%s ", ::lstrlen(szOriginalString), szOriginalString); printf("密文字符串: [%d]%s ", strEncryptString_Mem.length(), strEncryptString_Mem.c_str()); printf("明文字符串: [%d]%s ", strDecryptString_Mem.length(), strDecryptString_Mem.c_str()); system("pause"); return 0;
到此,關(guān)于“C/C++ Crypto密碼庫(kù)如何調(diào)用”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。