Um ein C++-Programm zur Berechnung des SHA-256-Hashes eines Strings zu schreiben, ohne die OpenSSL-Bibliothek zu verwenden, können wir die C++17-Standardbibliothek und die < CommonCrypto/CommonDigest.h>-Bibliothek auf macOS verwenden. Auf Windows können wir die Windows Cryptographic API verwenden. Hier ist ein Beispiel für macOS:
Für Windows kannst du die folgende Lösung verwenden, die die Windows Cryptographic API verwendet:
cpp
#include <iostream>
#include <string>
#include <windows.h>
#include <wincrypt.h>
std::string sha256(const std::string& str) {
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
LPBYTE pbHash = NULL;
DWORD cbHash = 0;
DWORD cbData = str.size();
BYTE* rgbData = (BYTE*)str.c_str();
std::string hash;
// Get a handle to the crypto provider
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
std::cerr << "CryptAcquireContext failed: " << GetLastError() << std::endl;
return hash;
}
// Create an empty hash object
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
std::cerr << "CryptCreateHash failed: " << GetLastError() << std::endl;
CryptReleaseContext(hProv, 0);
return hash;
}
// Hash the data
if (!CryptHashData(hHash, rgbData, cbData, 0)) {
std::cerr << "CryptHashData failed: " << GetLastError() << std::endl;
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return hash;
}
// Get the hash value
cbHash = CC_SHA256_DIGEST_LENGTH;
pbHash = (LPBYTE)malloc(cbHash);
if (NULL == pbHash) {
std::cerr << "Memory allocation failed" << std::endl;
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return hash;
}
if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0)) {
std::cerr << "CryptGetHashParam failed: " << GetLastError() << std::endl;
free(pbHash);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return hash;
}
// Convert the hash to a string
hash.resize(cbHash * 2);
for (DWORD i = 0; i < cbHash; i++) {
sprintf_s((char*)&hash[i * 2], 3, "%02x", pbHash[i]);
}
// Clean up
free(pbHash);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return hash;
}
int main() {
std::string input;
std::cout << "Enter a string to hash: ";
std::getline(std::cin, input);
std::string hash = sha256(input);
std::cout << "SHA-256 Hash: " << hash << std::endl;
return 0;
}
Diese Programme verwenden die Standard-APIs der Betriebssysteme, um den SHA-256-Hash eines Strings zu berechnen, ohne die OpenSSL-Bibliothek zu verwenden.