您好,登錄后才能下訂單哦!
這篇文章主要介紹“C/C++ Crypto密碼庫如何調用”,在日常操作中,相信很多人在C/C++ Crypto密碼庫如何調用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C/C++ Crypto密碼庫如何調用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
Sha系列加密算法包括很多,基本上有以下幾種格式的加密方式,位數越大加密強度越大,此算法屬于單向加密算法與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; } // 計算數據的 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; // 計算一個數組 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 << "計算數組的MD5: " << dst << endl; // 直接對文件計算Sha256散列值 string sha = CalSHA256_ByFile("c://BuidIAT.exe"); cout << "文件散列值: " << sha << endl; // 讀入文件到內存后計算 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 << "內存中文件散列值: " << sha2.c_str() << endl; system("pause"); return 0; }
AES是對稱加密,AES可使用16,24或32字節密鑰(分別對應128,192和256位)。 Crypto++ 庫缺省的密鑰長度是16字節,也就是 AES:: DEFAULT_KEYLENGTH。
對于 ECB 和 CBC 模式,處理的數據必須是塊大小的倍數。或者,你可以用 StreamTransformationFilter 圍繞這個模式對象,并把它作為一個過濾器對象。StreamTransformationFilter 能夠緩存數據到塊中并根據需要填充。
#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; // 產生一個隨機數的密鑰 SecByteBlock Key(0x00, AES::DEFAULT_KEYLENGTH); rand.GenerateBlock(Key, Key.size()); // 產生一個隨機的初始向量 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 << "顯示加密后的十六進制數: "; StringSource strSource1(plainText, Textlen, true, new HexEncoder(new FileSink(cout))); // 解密字符串 并將數據輸出到Cout流上 CFB_Mode<AES>::Decryption cfbDecryption(Key, Key.size(), ival); cfbDecryption.ProcessData(plainText, plainText, Textlen); cout << endl << "顯示解密后的十六進制數: "; StringSource strSource2(plainText, Textlen, true, new HexEncoder(new FileSink(cout))); cout << endl; system("pause"); return 0; }
以下代碼使用CBC模式加密與解密指定字符串。如果需要針對字符串進行加解密則需要使用以下代碼實現.
#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; // 創建并開始加密字符串 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模式實現快速對字符串進行加解密,該模式的數據的長度并不需要是AES的塊大小的倍數.
#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; // 執行快速加密 CFB_Mode<AES>::Encryption cfbEncryption(key, key.size(), iv); cfbEncryption.ProcessData((byte*)plainText, (byte*)plainText, messageLen); cout << "加密后的數據: " << plainText << endl; // 執行快速解密 CFB_Mode<AES>::Decryption cfbDecryption(key, key.size(), iv); cfbDecryption.ProcessData((byte*)plainText, (byte*)plainText, messageLen); cout << "解密后的數據: " << 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; // 創建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; // 加密數據 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; // 創建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; // 解密數據 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); // 原始十六進制數據 printf("AES 原始數據 [%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"; // 對字符串編碼 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 << "編碼后的數據: " << 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值.
#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; // 創建一個HASH對象, 指定HASH算法 bRet = CryptCreateHash(hCryptProv, algHashType, NULL, NULL, &hCryptHash); if (FALSE == bRet) break; // 計算HASH數據 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; // 申請內存 pHashData = new BYTE[dwHashDataLength]; if (NULL == pHashData) { bRet = FALSE; break; } RtlZeroMemory(pHashData, dwHashDataLength); // 獲取HASH結果數據 bRet = CryptGetHashParam(hCryptHash, HP_HASHVAL, pHashData, &dwHashDataLength, 0); if (FALSE == bRet) break; // 返回數據 *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; // 獲取文件流數據 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(" ", 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(" ", 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(" ", dwHashDataLength); if (pHashData) { delete[]pHashData; pHashData = NULL; } system("pause"); return 0; }
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; // 獲取公鑰密鑰的長度和內容 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; // 獲取私鑰密鑰的長度和內容 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; // 返回數據 *ppPublicKey = pPublicKey; *pdwPublicKeyLength = dwPublicKeyLength; *ppPrivateKey = pPrivateKey; *pdwPrivateKeyLength = dwPrivateKeyLength; } while (FALSE); // 釋放關閉 if (hCryptKey) CryptDestroyKey(hCryptKey); if (hCryptProv) CryptReleaseContext(hCryptProv, 0); return bRet; } // 公鑰加密數據 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; // 加密數據 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; } // 私鑰解密數據 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; // 解密數據 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); // 輸出加密前原始數據 printf("加密前原始數據: "); 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加密一般使用公鑰加密私鑰解密,先生成公鑰與私鑰,然后使用這兩份密鑰對字符串等數據進行操作.
#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; // 定義全局隨機數池 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; } /* 通過在內存中的密鑰對進行加密與解密 */ // 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"; // 指定一串隨機數種子 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("原文字符串: [%d]%s ", lstrlen(szOriginalString), szOriginalString); printf("密文字符串: [%d]%s ", strEncryptString.length(), strEncryptString.c_str()); printf("明文字符串: [%d]%s ", strDecryptString.length(), strDecryptString.c_str()); printf(" "); // -------------------------------------------------------------------------------------------------------------- /* 此處是在內存中對指定字符串進行解密*/ 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;
到此,關于“C/C++ Crypto密碼庫如何調用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。