#include "sha.h"
#include <cstring>

// ─── SHA-256 with SHA-NI hardware acceleration (runtime dispatch) ───
#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)
#include <immintrin.h>

#if defined(__GNUC__) || defined(__clang__)
__attribute__((target("sha,sse4.1")))
#endif
static std::vector<uint8_t> sha256_hash_shani(const std::vector<uint8_t>& input) {
    // SHA-256 initial state
    alignas(16) static const uint32_t H0[4] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a};
    alignas(16) static const uint32_t H1[4] = {0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
    static const uint32_t K256[64] = {
        0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
        0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
        0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
        0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
        0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
        0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
        0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
        0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
    };
    const __m128i MASK = _mm_set_epi64x(0x0c0d0e0f08090a0bULL, 0x0405060700010203ULL);

    // Padding
    std::vector<uint8_t> msg = input;
    uint64_t bitLen = (uint64_t)input.size() * 8;
    msg.push_back(0x80);
    while ((msg.size() + 8) % 64 != 0) msg.push_back(0x00);
    for (int i = 7; i >= 0; --i) msg.push_back((bitLen >> (i * 8)) & 0xFF);

    // Init state: SHA-NI uses DCBA / HGFE layout (reversed within 128-bit)
    __m128i STATE0 = _mm_loadu_si128((const __m128i*)H0);
    __m128i STATE1 = _mm_loadu_si128((const __m128i*)H1);
    // Rearrange: STATE0 = ABEF, STATE1 = CDGH (for _mm_sha256rnds2_epu32)
    __m128i TMP = _mm_shuffle_epi32(STATE0, 0xB1); // BADC
    STATE1 = _mm_shuffle_epi32(STATE1, 0x1B);      // HGFE
    STATE0 = _mm_alignr_epi8(TMP, STATE1, 8);      // ABEF
    STATE1 = _mm_blend_epi16(STATE1, TMP, 0xF0);   // CDGH

    for (size_t offset = 0; offset < msg.size(); offset += 64) {
        __m128i ABEF_SAVE = STATE0;
        __m128i CDGH_SAVE = STATE1;

        __m128i MSG0 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i*)(msg.data() + offset +  0)), MASK);
        __m128i MSG1 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i*)(msg.data() + offset + 16)), MASK);
        __m128i MSG2 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i*)(msg.data() + offset + 32)), MASK);
        __m128i MSG3 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i*)(msg.data() + offset + 48)), MASK);

        __m128i MSGTMP;

        // State update macro — 4 SHA-256 rounds using msg + K[ki]
        #define SHANI_ROUNDS(msg, ki) \
            MSGTMP = _mm_add_epi32(msg, _mm_loadu_si128((const __m128i*)&K256[ki])); \
            STATE1 = _mm_sha256rnds2_epu32(STATE1, STATE0, MSGTMP); \
            MSGTMP = _mm_shuffle_epi32(MSGTMP, 0x0E); \
            STATE0 = _mm_sha256rnds2_epu32(STATE0, STATE1, MSGTMP);

        // Full round: state update + complete `next` W expansion + start partial `pa`
        // `cur` = current fully-computed W, used for round keys
        // `next` = message to complete (already has sha256msg1 applied)
        // `pa`   = prev for alignr AND target for sha256msg1 (same register)
        #define SHANI_FULL_ROUND(ki, cur, next, pa) \
            SHANI_ROUNDS(cur, ki); \
            next = _mm_add_epi32(next, _mm_alignr_epi8(cur, pa, 4)); \
            next = _mm_sha256msg2_epu32(next, cur); \
            pa = _mm_sha256msg1_epu32(pa, cur);

        // Rounds 0-3
        SHANI_ROUNDS(MSG0, 0);
        // Rounds 4-7
        SHANI_ROUNDS(MSG1, 4);
        MSG0 = _mm_sha256msg1_epu32(MSG0, MSG1);
        // Rounds 8-11
        SHANI_ROUNDS(MSG2, 8);
        MSG1 = _mm_sha256msg1_epu32(MSG1, MSG2);
        // Rounds 12-15
        SHANI_ROUNDS(MSG3, 12);
        MSG0 = _mm_add_epi32(MSG0, _mm_alignr_epi8(MSG3, MSG2, 4));
        MSG0 = _mm_sha256msg2_epu32(MSG0, MSG3);
        MSG2 = _mm_sha256msg1_epu32(MSG2, MSG3);

        // Rounds 16-55: repeating pattern — use cur, complete next, start pa
        SHANI_FULL_ROUND(16, MSG0, MSG1, MSG3);
        SHANI_FULL_ROUND(20, MSG1, MSG2, MSG0);
        SHANI_FULL_ROUND(24, MSG2, MSG3, MSG1);
        SHANI_FULL_ROUND(28, MSG3, MSG0, MSG2);
        SHANI_FULL_ROUND(32, MSG0, MSG1, MSG3);
        SHANI_FULL_ROUND(36, MSG1, MSG2, MSG0);
        SHANI_FULL_ROUND(40, MSG2, MSG3, MSG1);
        SHANI_FULL_ROUND(44, MSG3, MSG0, MSG2);
        SHANI_FULL_ROUND(48, MSG0, MSG1, MSG3);
        SHANI_FULL_ROUND(52, MSG1, MSG2, MSG0);

        // Rounds 56-59: last expansion (complete MSG3, no new partial needed)
        SHANI_ROUNDS(MSG2, 56);
        MSG3 = _mm_add_epi32(MSG3, _mm_alignr_epi8(MSG2, MSG1, 4));
        MSG3 = _mm_sha256msg2_epu32(MSG3, MSG2);

        // Rounds 60-63: final rounds, no expansion
        SHANI_ROUNDS(MSG3, 60);

        #undef SHANI_ROUNDS
        #undef SHANI_FULL_ROUND

        STATE0 = _mm_add_epi32(STATE0, ABEF_SAVE);
        STATE1 = _mm_add_epi32(STATE1, CDGH_SAVE);
    }

    // Rearrange back to ABCDEFGH and byte-swap to big-endian
    TMP = _mm_shuffle_epi32(STATE0, 0x1B);        // FEBA
    STATE1 = _mm_shuffle_epi32(STATE1, 0xB1);     // DCHG
    STATE0 = _mm_blend_epi16(TMP, STATE1, 0xF0);  // DCBA
    STATE1 = _mm_alignr_epi8(STATE1, TMP, 8);     // HGFE

    STATE0 = _mm_shuffle_epi8(STATE0, MASK);
    STATE1 = _mm_shuffle_epi8(STATE1, MASK);

    std::vector<uint8_t> hash(32);
    _mm_storeu_si128((__m128i*)hash.data(), STATE0);
    _mm_storeu_si128((__m128i*)(hash.data() + 16), STATE1);
    return hash;
}

static bool cpu_has_shani() {
#if defined(__SHA__)
    // Compiled with -msha, assume CPU supports it
    return true;
#elif defined(__GNUC__) || defined(__clang__)
  #if defined(__linux__) && !defined(__GLIBC__)
    // musl: use cpuid directly
    unsigned int eax, ebx, ecx, edx;
    __asm__ __volatile__("cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
                         : "a"(7), "c"(0));
    return (ebx >> 29) & 1; // SHA bit is bit 29 of EBX for CPUID leaf 7
  #else
    return __builtin_cpu_supports("sha");
  #endif
#else
    return false;
#endif
}
#endif // x86

std::vector<uint8_t> netplus::sha1_hash(const std::vector<uint8_t>& input) {

    #define SHA1_ROL(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))

    // 1. Initial State
    uint32_t h0 = 0x67452301, h1 = 0xEFCDAB89, h2 = 0x98BADCFE, h3 = 0x10325476, h4 = 0xC3D2E1F0;

    // 2. Pre-processing (Padding)
    std::vector<uint8_t> msg = input;
    uint64_t bitLen = (uint64_t)input.size() * 8;
    msg.push_back(0x80); // Append '1' bit
    while ((msg.size() + 8) % 64 != 0) msg.push_back(0x00);

    // Append length in bits as 64-bit big-endian integer
    for (int i = 7; i >= 0; --i) msg.push_back((bitLen >> (i * 8)) & 0xFF);

    // 3. Process in 512-bit blocks
    for (size_t offset = 0; offset < msg.size(); offset += 64) {
        uint32_t w[80];
        // Break block into sixteen 32-bit big-endian words
        for (int i = 0; i < 16; ++i) {
            w[i] = (msg[offset + i * 4] << 24) | (msg[offset + i * 4 + 1] << 16) |
                   (msg[offset + i * 4 + 2] << 8) | (msg[offset + i * 4 + 3]);
        }
        // Extend sixteen words into eighty words
        for (int i = 16; i < 80; ++i)
            w[i] = SHA1_ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);

        uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;

        // Main Loop
        for (int i = 0; i < 80; ++i) {
            uint32_t f, k;
            if (i < 20) {
                f = (b & c) | ((~b) & d);
                k = 0x5A827999;
            } else if (i < 40) {
                f = b ^ c ^ d;
                k = 0x6ED9EBA1;
            } else if (i < 60) {
                f = (b & c) | (b & d) | (c & d);
                k = 0x8F1BBCDC;
            } else {
                f = b ^ c ^ d;
                k = 0xCA62C1D6;
            }
            uint32_t temp = SHA1_ROL(a, 5) + f + e + k + w[i];
            e = d; d = c;
            c = SHA1_ROL(b, 30);
            b = a; a = temp;
        }
        h0 += a; h1 += b; h2 += c; h3 += d; h4 += e;
    }

    // 4. Produce final hash (20 bytes)
    std::vector<uint8_t> hash(20);
    uint32_t states[5] = {h0, h1, h2, h3, h4};
    for (int i = 0; i < 5; ++i) {
        hash[i * 4]     = (states[i] >> 24) & 0xFF;
        hash[i * 4 + 1] = (states[i] >> 16) & 0xFF;
        hash[i * 4 + 2] = (states[i] >> 8) & 0xFF;
        hash[i * 4 + 3] = states[i] & 0xFF;
    }
    return hash;
}

std::vector<uint8_t> netplus::sha256_hash(const std::vector<uint8_t>& input) {
#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)
    static const bool has_shani = cpu_has_shani();
    if (has_shani) return sha256_hash_shani(input);
#endif

    // SHA-256 - correct implementation based on FIPS 180-4
    #define SHA256_ROR(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits))))

    #define SHA256_SIG0(x) (SHA256_ROR(x, 7)  ^ SHA256_ROR(x, 18) ^ ((x) >> 3))
    #define SHA256_SIG1(x) (SHA256_ROR(x, 17) ^ SHA256_ROR(x, 19) ^ ((x) >> 10))
    #define SHA256_EPS0(x) (SHA256_ROR(x, 2)  ^ SHA256_ROR(x, 13) ^ SHA256_ROR(x, 22))
    #define SHA256_EPS1(x) (SHA256_ROR(x, 6)  ^ SHA256_ROR(x, 11) ^ SHA256_ROR(x, 25))

    // 1. Initial State (First 32 bits of the fractional parts of the square roots of the first 8 primes)
    uint32_t h[8] = {
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
        0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
    };

    // 2. Constants (First 32 bits of the fractional parts of the cube roots of the first 64 primes)
    static const uint32_t k[64] = {
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
    };

    // 3. Pre-processing (Padding) - Same logic as SHA-1
    std::vector<uint8_t> msg = input;
    uint64_t bitLen = (uint64_t)input.size() * 8;
    msg.push_back(0x80);
    while ((msg.size() + 8) % 64 != 0) msg.push_back(0x00);

    // Append length as 64-bit big-endian
    for (int i = 7; i >= 0; --i) msg.push_back((bitLen >> (i * 8)) & 0xFF);

    // 4. Process in 512-bit blocks
    for (size_t offset = 0; offset < msg.size(); offset += 64) {
        uint32_t w[64];
        for (int i = 0; i < 16; ++i) {
            w[i] = (msg[offset + i * 4] << 24) | (msg[offset + i * 4 + 1] << 16) |
                   (msg[offset + i * 4 + 2] << 8) | (msg[offset + i * 4 + 3]);
        }
        for (int i = 16; i < 64; ++i) {
            w[i] = SHA256_SIG1(w[i - 2]) + w[i - 7] + SHA256_SIG0(w[i - 15]) + w[i - 16];
        }

        uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], l = h[7];

        for (int i = 0; i < 64; ++i) {
            uint32_t t1 = l +  SHA256_EPS1(e) + ((e & f) ^ (~e & g)) + k[i] + w[i];
            uint32_t t2 = SHA256_EPS0(a) + ((a & b) ^ (a & c) ^ (b & c));
            l = g; g = f; f = e;
            e = d + t1;
            d = c; c = b; b = a;
            a = t1 + t2;
        }

        h[0] += a; h[1] += b; h[2] += c; h[3] += d;
        h[4] += e; h[5] += f; h[6] += g; h[7] += l;
    }

    // 5. Produce final hash (32 bytes)
    std::vector<uint8_t> hash(32);
    for (int i = 0; i < 8; ++i) {
        hash[i * 4]     = (h[i] >> 24) & 0xFF;
        hash[i * 4 + 1] = (h[i] >> 16) & 0xFF;
        hash[i * 4 + 2] = (h[i] >> 8) & 0xFF;
        hash[i * 4 + 3] = h[i] & 0xFF;
    }
    return hash;
}

// SHA-384: Native implementation (SHA-512 with different IVs, truncated to 48 bytes)
std::vector<uint8_t> netplus::sha384_hash(const std::vector<uint8_t>& input) {
    #define SHA512_ROR(value, bits) (((value) >> (bits)) | ((value) << (64 - (bits))))

    #define SHA512_SIG0(x) (SHA512_ROR(x, 1)  ^ SHA512_ROR(x, 8)  ^ ((x) >> 7))
    #define SHA512_SIG1(x) (SHA512_ROR(x, 19) ^ SHA512_ROR(x, 61) ^ ((x) >> 6))
    #define SHA512_EPS0(x) (SHA512_ROR(x, 28) ^ SHA512_ROR(x, 34) ^ SHA512_ROR(x, 39))
    #define SHA512_EPS1(x) (SHA512_ROR(x, 14) ^ SHA512_ROR(x, 18) ^ SHA512_ROR(x, 41))

    // SHA-384 initial hash values (from the fractional parts of the square roots of the 9th-16th primes)
    uint64_t h[8] = {
        0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL,
        0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,
        0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL,
        0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL
    };

    // SHA-512 round constants
    static const uint64_t k[80] = {
        0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
        0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
        0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
        0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
        0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
        0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
        0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
        0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
        0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
        0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
        0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
        0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
        0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
        0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
        0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
        0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
        0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
        0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
        0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
        0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
    };

    // Pre-processing (Padding)
    std::vector<uint8_t> msg = input;
    uint64_t bitLen = (uint64_t)input.size() * 8;
    msg.push_back(0x80);
    while ((msg.size() + 16) % 128 != 0) msg.push_back(0x00);

    // Append length as 128-bit big-endian (high 64 bits are 0 for practical sizes)
    for (int i = 7; i >= 0; --i) msg.push_back(0x00);
    for (int i = 7; i >= 0; --i) msg.push_back((uint8_t)((bitLen >> (i * 8)) & 0xFF));

    // Process in 1024-bit blocks
    for (size_t offset = 0; offset < msg.size(); offset += 128) {
        uint64_t w[80];
        for (int i = 0; i < 16; ++i) {
            w[i] = ((uint64_t)msg[offset + i * 8    ] << 56) | ((uint64_t)msg[offset + i * 8 + 1] << 48) |
                   ((uint64_t)msg[offset + i * 8 + 2] << 40) | ((uint64_t)msg[offset + i * 8 + 3] << 32) |
                   ((uint64_t)msg[offset + i * 8 + 4] << 24) | ((uint64_t)msg[offset + i * 8 + 5] << 16) |
                   ((uint64_t)msg[offset + i * 8 + 6] <<  8) | ((uint64_t)msg[offset + i * 8 + 7]);
        }
        for (int i = 16; i < 80; ++i) {
            w[i] = SHA512_SIG1(w[i - 2]) + w[i - 7] + SHA512_SIG0(w[i - 15]) + w[i - 16];
        }

        uint64_t a = h[0], b = h[1], c = h[2], d = h[3],
                 e = h[4], f = h[5], g = h[6], l = h[7];

        for (int i = 0; i < 80; ++i) {
            uint64_t t1 = l + SHA512_EPS1(e) + ((e & f) ^ (~e & g)) + k[i] + w[i];
            uint64_t t2 = SHA512_EPS0(a) + ((a & b) ^ (a & c) ^ (b & c));
            l = g; g = f; f = e;
            e = d + t1;
            d = c; c = b; b = a;
            a = t1 + t2;
        }

        h[0] += a; h[1] += b; h[2] += c; h[3] += d;
        h[4] += e; h[5] += f; h[6] += g; h[7] += l;
    }

    // Produce final hash - SHA-384 uses first 6 words of SHA-512 state (48 bytes)
    std::vector<uint8_t> hash(48);
    for (int i = 0; i < 6; ++i) {
        hash[i * 8]     = (h[i] >> 56) & 0xFF;
        hash[i * 8 + 1] = (h[i] >> 48) & 0xFF;
        hash[i * 8 + 2] = (h[i] >> 40) & 0xFF;
        hash[i * 8 + 3] = (h[i] >> 32) & 0xFF;
        hash[i * 8 + 4] = (h[i] >> 24) & 0xFF;
        hash[i * 8 + 5] = (h[i] >> 16) & 0xFF;
        hash[i * 8 + 6] = (h[i] >>  8) & 0xFF;
        hash[i * 8 + 7] = h[i] & 0xFF;
    }
    return hash;

    #undef SHA512_ROR
    #undef SHA512_SIG0
    #undef SHA512_SIG1
    #undef SHA512_EPS0
    #undef SHA512_EPS1
}

// HMAC-SHA256 implementation
std::vector<uint8_t> netplus::hmac_sha256(const std::vector<uint8_t>& key,
                                          const std::vector<uint8_t>& msg) {
    constexpr size_t B = 64;   // SHA-256 block size
    constexpr size_t D = 32;   // SHA-256 output size

    // Lambda for secure zeroing - wipes sensitive data to prevent leakage
    auto secure_zero = [](std::vector<uint8_t>& v) {
#if defined(__STDC_LIB_EXT1__)
        if (!v.empty()) memset_s(v.data(), v.size(), 0, v.size());
#else
        volatile uint8_t* p = v.empty() ? nullptr : v.data();
        for (size_t i = 0; p && i < v.size(); ++i) p[i] = 0;
#endif
    };

    // Step 1: K0 = key normalized to block size B
    std::vector<uint8_t> K0;
    K0.reserve(B);

    if (key.size() > B) {
        K0 = sha256_hash(key);              // 32 bytes
        K0.resize(B, 0x00);                 // pad to 64
    } else {
        K0 = key;
        K0.resize(B, 0x00);
    }

    // Step 2: ipad/opad
    std::vector<uint8_t> ipad(B), opad(B);
    for (size_t i = 0; i < B; ++i) {
        ipad[i] = static_cast<uint8_t>(K0[i] ^ 0x36);
        opad[i] = static_cast<uint8_t>(K0[i] ^ 0x5c);
    }

    // Step 3: inner = H((K0^ipad) || msg)
    std::vector<uint8_t> inner_input;
    inner_input.reserve(B + msg.size());
    inner_input.insert(inner_input.end(), ipad.begin(), ipad.end());
    inner_input.insert(inner_input.end(), msg.begin(), msg.end());
    std::vector<uint8_t> inner = sha256_hash(inner_input);

    // Step 4: outer = H((K0^opad) || inner)
    std::vector<uint8_t> outer_input;
    outer_input.reserve(B + D);
    outer_input.insert(outer_input.end(), opad.begin(), opad.end());
    outer_input.insert(outer_input.end(), inner.begin(), inner.end());
    std::vector<uint8_t> mac = sha256_hash(outer_input);

    // Wipe sensitive buffers best-effort
    secure_zero(K0);
    secure_zero(ipad);
    secure_zero(opad);
    secure_zero(inner_input);
    secure_zero(outer_input);
    secure_zero(inner);

    return mac; // 32 bytes
}

// HMAC-SHA384 implementation
std::vector<uint8_t> netplus::hmac_sha384(const std::vector<uint8_t>& key,
                                          const std::vector<uint8_t>& msg) {
    constexpr size_t B = 128;  // SHA-512 block size (also for SHA-384)
    constexpr size_t D = 48;   // SHA-384 output size

    // Lambda for secure zeroing - wipes sensitive data to prevent leakage
    auto secure_zero = [](std::vector<uint8_t>& v) {
#if defined(__STDC_LIB_EXT1__)
        if (!v.empty()) memset_s(v.data(), v.size(), 0, v.size());
#else
        // Best-effort portable wipe (compiler might optimize away in some builds).
        volatile uint8_t* p = v.empty() ? nullptr : v.data();
        for (size_t i = 0; p && i < v.size(); ++i) p[i] = 0;
#endif
    };

    // Step 1: K0 = key normalized to block size B
    std::vector<uint8_t> K0;
    K0.reserve(B);

    if (key.size() > B) {
        K0 = sha384_hash(key);              // 48 bytes
        K0.resize(B, 0x00);                 // pad to 128
    } else {
        K0 = key;
        K0.resize(B, 0x00);
    }

    // Step 2: ipad/opad
    std::vector<uint8_t> ipad(B), opad(B);
    for (size_t i = 0; i < B; ++i) {
        ipad[i] = static_cast<uint8_t>(K0[i] ^ 0x36);
        opad[i] = static_cast<uint8_t>(K0[i] ^ 0x5c);
    }

    // Step 3: inner = H((K0^ipad) || msg)
    std::vector<uint8_t> inner_input;
    inner_input.reserve(B + msg.size());
    inner_input.insert(inner_input.end(), ipad.begin(), ipad.end());
    inner_input.insert(inner_input.end(), msg.begin(), msg.end());
    std::vector<uint8_t> inner = sha384_hash(inner_input);

    // Step 4: outer = H((K0^opad) || inner)
    std::vector<uint8_t> outer_input;
    outer_input.reserve(B + D);
    outer_input.insert(outer_input.end(), opad.begin(), opad.end());
    outer_input.insert(outer_input.end(), inner.begin(), inner.end());
    std::vector<uint8_t> mac = sha384_hash(outer_input);

    // Wipe sensitive buffers best-effort
    secure_zero(K0);
    secure_zero(ipad);
    secure_zero(opad);
    secure_zero(inner_input);
    secure_zero(outer_input);
    secure_zero(inner);

    return mac; // 48 bytes
}

// Constant-time comparison for HMAC verification
bool netplus::hmac_sha384_verify(const std::vector<uint8_t>& key,
                                 const std::vector<uint8_t>& msg,
                                 const std::vector<uint8_t>& mac) {
    
    auto ct_equal = [](const uint8_t* a, const uint8_t* b, size_t len) {
        uint8_t result = 0;
        for (size_t i = 0; i < len; ++i) {
            result |= a[i] ^ b[i];
        }
        return result == 0;
    };

    if (mac.size() != 48) return false; // length check is fine
    std::vector<uint8_t> expected = hmac_sha384(key, msg);
    bool ok = ct_equal(expected.data(), mac.data(), 48);
    
    // Wipe expected MAC from memory
    volatile uint8_t* p = expected.data();
    for (size_t i = 0; i < expected.size(); ++i) p[i] = 0;
    
    return ok;
}

// HMAC-SHA1 implementation (RFC 2104 with SHA-1)
// Needed for Kerberos RFC 3962 PBKDF2-HMAC-SHA1 string-to-key
std::vector<uint8_t> netplus::hmac_sha1(const std::vector<uint8_t>& key,
                                        const std::vector<uint8_t>& msg) {
    constexpr size_t B = 64;   // SHA-1 block size
    constexpr size_t D = 20;   // SHA-1 output size

    auto secure_zero = [](std::vector<uint8_t>& v) {
        volatile uint8_t* p = v.empty() ? nullptr : v.data();
        for (size_t i = 0; p && i < v.size(); ++i) p[i] = 0;
    };

    // Step 1: K0 = key normalized to block size B
    std::vector<uint8_t> K0;
    K0.reserve(B);

    if (key.size() > B) {
        K0 = sha1_hash(key);               // 20 bytes
        K0.resize(B, 0x00);                // pad to 64
    } else {
        K0 = key;
        K0.resize(B, 0x00);
    }

    // Step 2: ipad/opad
    std::vector<uint8_t> ipad(B), opad(B);
    for (size_t i = 0; i < B; ++i) {
        ipad[i] = static_cast<uint8_t>(K0[i] ^ 0x36);
        opad[i] = static_cast<uint8_t>(K0[i] ^ 0x5c);
    }

    // Step 3: inner = SHA1((K0^ipad) || msg)
    std::vector<uint8_t> inner_input;
    inner_input.reserve(B + msg.size());
    inner_input.insert(inner_input.end(), ipad.begin(), ipad.end());
    inner_input.insert(inner_input.end(), msg.begin(), msg.end());
    std::vector<uint8_t> inner = sha1_hash(inner_input);

    // Step 4: outer = SHA1((K0^opad) || inner)
    std::vector<uint8_t> outer_input;
    outer_input.reserve(B + D);
    outer_input.insert(outer_input.end(), opad.begin(), opad.end());
    outer_input.insert(outer_input.end(), inner.begin(), inner.end());
    std::vector<uint8_t> mac = sha1_hash(outer_input);

    // Wipe sensitive buffers
    secure_zero(K0);
    secure_zero(ipad);
    secure_zero(opad);
    secure_zero(inner_input);
    secure_zero(outer_input);
    secure_zero(inner);

    return mac; // 20 bytes
}

// Constant-time HMAC-SHA1 verification
bool netplus::hmac_sha1_verify(const std::vector<uint8_t>& key,
                               const std::vector<uint8_t>& msg,
                               const std::vector<uint8_t>& mac) {
    auto ct_equal = [](const uint8_t* a, const uint8_t* b, size_t len) {
        uint8_t result = 0;
        for (size_t i = 0; i < len; ++i) {
            result |= a[i] ^ b[i];
        }
        return result == 0;
    };

    if (mac.size() != 20) return false;
    std::vector<uint8_t> expected = hmac_sha1(key, msg);
    bool ok = ct_equal(expected.data(), mac.data(), 20);

    volatile uint8_t* p = expected.data();
    for (size_t i = 0; i < expected.size(); ++i) p[i] = 0;

    return ok;
}

// PBKDF2 with pluggable HMAC (RFC 2898 / RFC 8018)
std::vector<uint8_t> netplus::pbkdf2(
    const std::vector<uint8_t>& password,
    const std::vector<uint8_t>& salt,
    uint32_t iterations,
    size_t dkLen,
    size_t hmacLen,
    std::vector<uint8_t>(*hmacFunc)(const std::vector<uint8_t>&,
                                    const std::vector<uint8_t>&))
{
    size_t blocks = (dkLen + hmacLen - 1) / hmacLen;
    std::vector<uint8_t> result;
    result.reserve(blocks * hmacLen);

    for (size_t i = 1; i <= blocks; ++i) {
        // U_1 = HMAC(password, salt || INT_32_BE(i))
        std::vector<uint8_t> saltBlock = salt;
        saltBlock.push_back(static_cast<uint8_t>((i >> 24) & 0xFF));
        saltBlock.push_back(static_cast<uint8_t>((i >> 16) & 0xFF));
        saltBlock.push_back(static_cast<uint8_t>((i >> 8) & 0xFF));
        saltBlock.push_back(static_cast<uint8_t>(i & 0xFF));

        auto u = hmacFunc(password, saltBlock);
        auto xorResult = u;

        for (uint32_t j = 1; j < iterations; ++j) {
            u = hmacFunc(password, u);
            for (size_t k = 0; k < hmacLen && k < u.size(); ++k)
                xorResult[k] ^= u[k];
        }

        result.insert(result.end(), xorResult.begin(), xorResult.end());
    }

    result.resize(dkLen);
    return result;
}

// Convenience: PBKDF2-HMAC-SHA1 (RFC 3962 Kerberos string-to-key)
std::vector<uint8_t> netplus::pbkdf2_hmac_sha1(
    const std::vector<uint8_t>& password,
    const std::vector<uint8_t>& salt,
    uint32_t iterations,
    size_t dkLen)
{
    return pbkdf2(password, salt, iterations, dkLen, 20, hmac_sha1);
}

// Convenience: PBKDF2-HMAC-SHA256
std::vector<uint8_t> netplus::pbkdf2_hmac_sha256(
    const std::vector<uint8_t>& password,
    const std::vector<uint8_t>& salt,
    uint32_t iterations,
    size_t dkLen)
{
    return pbkdf2(password, salt, iterations, dkLen, 32, hmac_sha256);
}

