[C++] 使用 openssl 函式庫,計算檔案的 SHA1 值

[C++] 使用 openssl 函式庫,計算檔案的 SHA1 值

今天用 C++ 呼叫 openssl 來計算一個檔案的 SHA1 值,

簡單用這篇記錄一下寫完的函式吧:

#include <openssl/sha.h>
std::string CalcFileSHA1(const char* pFilePath)
{
std::string sResult = "";
if (pFilePath != NULL && *pFilePath != '\0')
{
FILE* pf = fopen(pFilePath, "rb");
if (pf)
{
// Initialize sha1 context
SHA_CTX ctx = {};
int nRet = SHA1_Init(&ctx);
if (nRet == SHA_FUNC_RET_SUCCESS)
{
char buffer[2048] = {};
size_t nBytesRead = 0;
while (!feof(pf))
{
// Read some bytes
nBytesRead = fread(buffer, 1, sizeof(buffer), pf);
if (nBytesRead == 0)
{
break;
}
// Update bytes into sha1 context
if ((nRet = SHA1_Update(&ctx, buffer, nBytesRead)) != SHA_FUNC_RET_SUCCESS)
{
printf("Failed to update sha1 context while calculating sha1 of [%s]: nRet=%d\n", pFilePath, nRet);
break;
}
}
if (nRet == SHA_FUNC_RET_SUCCESS)
{
// Finalize sha1 calculation
if ((nRet = SHA1_Final(reinterpret_cast<unsigned char*>(buffer), &ctx)) == SHA_FUNC_RET_SUCCESS)
{
snprintf(buffer+SHA_DIGEST_LENGTH, sizeof(buffer)-SHA_DIGEST_LENGTH, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
static_cast<unsigned char>(buffer[0]),
static_cast<unsigned char>(buffer[1]),
static_cast<unsigned char>(buffer[2]),
static_cast<unsigned char>(buffer[3]),
static_cast<unsigned char>(buffer[4]),
static_cast<unsigned char>(buffer[5]),
static_cast<unsigned char>(buffer[6]),
static_cast<unsigned char>(buffer[7]),
static_cast<unsigned char>(buffer[8]),
static_cast<unsigned char>(buffer[9]),
static_cast<unsigned char>(buffer[10]),
static_cast<unsigned char>(buffer[11]),
static_cast<unsigned char>(buffer[12]),
static_cast<unsigned char>(buffer[13]),
static_cast<unsigned char>(buffer[14]),
static_cast<unsigned char>(buffer[15]),
static_cast<unsigned char>(buffer[16]),
static_cast<unsigned char>(buffer[17]),
static_cast<unsigned char>(buffer[18]),
static_cast<unsigned char>(buffer[19]));
sResult = buffer+SHA_DIGEST_LENGTH;
}
else
{
printf("Failed to finalize sha1 context while calculating sha1 of [%s]: nRet=%d\n", pFilePath, nRet);
}
}
}
else
{
printf("Failed to init sha1 context while calculating sha1 of [%s]: nRet=%d\n", pFilePath, nRet);
}
// Close file handle
fclose(pf);
}
else
{
printf("Failed to open [%s] to calculate sha1!\n", pFilePath);
}
}
else
{
printf("Invalid parameter for CalcFileSHA1: file path cannot be empty!\n");
}
return sResult;
}

 

編譯時記得要用 -lssl 來聯結 openssl 的函式庫: 

libtest.so: $(OBJ_FILES)
$(CC) $(CPPFLAGS) -o $@ $^ -rdynamic -shared -fPIC -lssl

 

(本頁面已被瀏覽過 567 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料