詳解C++中OpenSSL動態(tài)鏈接庫的使用
在上一篇文章 OpenSSL動態(tài)鏈接庫源碼安裝 中我們介紹了如何在Windows和Linux環(huán)境中編譯OpenSSL動態(tài)鏈接庫,這篇文章我們將介紹如何在C代碼中引用OpenSSL動態(tài)鏈接庫。
測試代碼
以下測試代碼 main.c 將分別在Windows和Linux環(huán)境中編譯,該代碼的作用是計算給定文件的SHA256值,
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include "openssl/sha.h"
void sha256_hash_string(unsigned char* hash, char* outputBuffer) {
size_t i = 0;
for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
sprintf(outputBuffer + (i * 2), "%02X", hash[i]);
}
}
int calc_sha256(char* filePath, char* output) {
FILE* file = fopen(filePath, "rb");
if (!file) {
return 1;
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
int bufferSize = 1024;
char* buffer = (char*)malloc(bufferSize * sizeof(char));
if (buffer == NULL) {
printf("Failed to invoke malloc function, buffer is NULL.\n");
return 1;
}
int bytesRead = 0;
while ((bytesRead = fread(buffer, sizeof(char), bufferSize, file))) {
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, output);
free(buffer);
fclose(file);
return 0;
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Please specify a file.\n");
return 1;
}
char* filePath = argv[1];
char calc_hash[65] = { 0 };
int rt = calc_sha256(filePath, calc_hash);
printf("SHA-256: %s\n", calc_hash);
return rt;
}
Windows上引用動態(tài)鏈接庫
創(chuàng)建VS工程,添加代碼,

配置頭文件和lib(注:是文件libcrypto.lib所在的目錄,而不是libcrypto-1_1-x64.dll的目錄)的引用目錄,Project -> SHA256 Properties -> VC++ Directories,

添加文件 libcrypto.lib,Project -> SHA256 Properties -> Linker -> Input,

此時可以完成編譯,但無法在VS中運行,會出現(xiàn)以下問題,

該錯誤提示無法找到dll文件,需要將dll目錄添加到運行時環(huán)境中,Project -> SHA256 Properties -> Debugging,

此時運行成功,

我們在命令行中手動運行可執(zhí)行文件??截愇募?strong> libcrypto-1_1-x64.dll 到可執(zhí)行文件所在目錄,運行可執(zhí)行文件,計算源文件 main.c 的SHA256??梢缘玫狡銼HA256為,
BEA6D328EA77FE8367DE573879A0245E1D9D23AF2A165745EE1E4D05EC004037

我們通過工具CertUtil來進行驗證,可以得到相同的Hash值,

注:使用VS編譯時需要指定lib文件libcrypto.lib,該文件本質(zhì)上是DLL文件libcrypto-1_1-x64.dll的描述,在這里并不是靜態(tài)鏈接庫文件。不完全清楚VS為什么一定需要該文件,使用gcc在Windows或Linux上編譯時不需要該lib文件,只需指定DLL文件即可。
Linux上引用動態(tài)鏈接庫
創(chuàng)建目錄: /home/sunny/work/build/SHA_256,將源文件 main.c 拷貝至該目錄,

執(zhí)行以下命令編譯源文件,生成可執(zhí)行文件 a.out,
gcc main.c -I/home/sunny/work/build/openssl/output/include -L/home/sunny/work/build/openssl/output/lib -lcrypto
這里,-I表示頭文件目錄,-L表示庫文件目錄,-l表示要引用的庫文件標識(庫文件名:libcrypto.so,其標識為crypto,要去掉lib和.so)。

運行可執(zhí)行文件,計算源文件main.c的SHA256,

可以看出,我們得到了相同的HASH值。
到此這篇關(guān)于OpenSSL動態(tài)鏈接庫的使用的文章就介紹到這了,更多相關(guān)OpenSSL動態(tài)鏈接庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ STL入門教程(7) multimap、multiset的使用
這篇文章主要介紹了C++ STL入門教程第七篇,multimap一對多索引,multiset多元集合的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
VC實現(xiàn)將網(wǎng)址解析出所有ip地址的實例代碼
這篇文章主要介紹了VC實現(xiàn)將網(wǎng)址解析出所有ip地址的實例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04

