S SmartDocs
시리즈: Algorithms cpp 78 줄 · 업데이트 2026-04-18

openssl_crypto_demo.cpp

Algorithms/Hash/cpp/openssl_crypto_demo.cpp

/**
 * SHA-256 digest + PBKDF2-HMAC-SHA256 (password-style derivation).
 *
 * Default build (no OpenSSL link): prints stub message.
 * Enable with compile flag and link libcrypto, e.g.:
 *   g++ -std=c++17 -O2 -DHASH_ENABLE_OPENSSL=1 openssl_crypto_demo.cpp \
 *     -I/opt/homebrew/opt/openssl@3/include \
 *     -L/opt/homebrew/opt/openssl@3/lib -lcrypto
 */
#if defined(HASH_ENABLE_OPENSSL) && HASH_ENABLE_OPENSSL

#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

#include <openssl/evp.h>
#include <openssl/sha.h>

static std::string toHex(const unsigned char* data, std::size_t len) {
    static const char* hex = "0123456789abcdef";
    std::string out(len * 2, ' ');
    for (std::size_t i = 0; i < len; ++i) {
        out[2 * i] = hex[data[i] >> 4];
        out[2 * i + 1] = hex[data[i] & 0xf];
    }
    return out;
}

static std::vector<unsigned char> sha256(const std::string& msg) {
    unsigned char md[SHA256_DIGEST_LENGTH];
    SHA256(reinterpret_cast<const unsigned char*>(msg.data()), msg.size(), md);
    return std::vector<unsigned char>(md, md + SHA256_DIGEST_LENGTH);
}

static std::vector<unsigned char> pbkdf2_hmac_sha256(const std::string& password,
                                                       const std::vector<unsigned char>& salt,
                                                       int iterations,
                                                       std::size_t outLen) {
    std::vector<unsigned char> out(outLen);
    if (PKCS5_PBKDF2_HMAC(password.data(), static_cast<int>(password.size()), salt.data(),
                          static_cast<int>(salt.size()), iterations, EVP_sha256(),
                          static_cast<int>(outLen), out.data()) != 1) {
        return {};
    }
    return out;
}

int main() {
    std::string msg = "hello";
    auto d = sha256(msg);
    std::cout << "SHA256(\"" << msg << "\") = " << toHex(d.data(), d.size()) << "\n";

    std::string password = "p@ssw0rd";
    std::vector<unsigned char> salt = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
    int iter = 100000;
    auto dk = pbkdf2_hmac_sha256(password, salt, iter, 32);
    if (dk.empty()) {
        std::cout << "PBKDF2 failed\n";
        return 1;
    }
    std::cout << "PBKDF2-HMAC-SHA256(iter=" << iter << ", salt=8 bytes, dkLen=32):\n";
    std::cout << toHex(dk.data(), dk.size()) << "\n";
    std::cout << "\nNote: bcrypt/Argon2 are preferred for interactive passwords; PBKDF2 is still common.\n";
    return 0;
}

#else

#include <iostream>

int main() {
    std::cout << "OpenSSL demo is disabled in this build.\n";
    std::cout << "Rebuild with -DHASH_ENABLE_OPENSSL=1 and link -lcrypto (plus -I/-L for OpenSSL).\n";
    return 0;
}

#endif

관련 글