// Copyright (C) 2026 Kiyotsugu Arai
// SPDX-License-Identifier: LGPL-3.0-or-later

// hash.hpp — SHA-256 / HMAC-SHA256
//
// FIPS 180-4 準拠の SHA-256 実装。外部依存なし、ヘッダオンリー。
//
// 使用例:
//   auto digest = calx::crypto::sha256("hello");
//   auto hex    = calx::crypto::sha256hex("hello");
//   // hex == "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

#ifndef CALX_CRYPTO_HASH_HPP
#define CALX_CRYPTO_HASH_HPP

#include <array>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

namespace calx::crypto {

    namespace detail_sha256 {

        // SHA-256 定数 (最初の 64 素数の立方根の小数部)
        inline constexpr 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
        };

        // SHA-256 初期ハッシュ値 (最初の 8 素数の平方根の小数部)
        inline constexpr uint32_t H0[8] = {
            0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
            0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
        };

        inline constexpr uint32_t rotr(uint32_t x, int n) {
            return (x >> n) | (x << (32 - n));
        }

        inline constexpr uint32_t Ch(uint32_t x, uint32_t y, uint32_t z) {
            return (x & y) ^ (~x & z);
        }

        inline constexpr uint32_t Maj(uint32_t x, uint32_t y, uint32_t z) {
            return (x & y) ^ (x & z) ^ (y & z);
        }

        // 大文字 Sigma
        inline constexpr uint32_t Sigma0(uint32_t x) {
            return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
        }

        inline constexpr uint32_t Sigma1(uint32_t x) {
            return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
        }

        // 小文字 sigma
        inline constexpr uint32_t sigma0(uint32_t x) {
            return rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3);
        }

        inline constexpr uint32_t sigma1(uint32_t x) {
            return rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10);
        }

        // big-endian 読み書き
        inline uint32_t load32be(const uint8_t* p) {
            return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) |
                   (uint32_t(p[2]) << 8)  |  uint32_t(p[3]);
        }

        inline void store32be(uint8_t* p, uint32_t v) {
            p[0] = uint8_t(v >> 24);
            p[1] = uint8_t(v >> 16);
            p[2] = uint8_t(v >> 8);
            p[3] = uint8_t(v);
        }

        // 1 ブロック (64 バイト) を処理
        inline void processBlock(uint32_t state[8], const uint8_t block[64]) {
            uint32_t W[64];

            // メッセージスケジュール展開
            for (int i = 0; i < 16; ++i)
                W[i] = load32be(block + 4 * i);
            for (int i = 16; i < 64; ++i)
                W[i] = sigma1(W[i - 2]) + W[i - 7] + sigma0(W[i - 15]) + W[i - 16];

            // 作業変数
            uint32_t a = state[0], b = state[1], c = state[2], d = state[3];
            uint32_t e = state[4], f = state[5], g = state[6], h = state[7];

            // 64 ラウンド
            for (int i = 0; i < 64; ++i) {
                uint32_t T1 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];
                uint32_t T2 = Sigma0(a) + Maj(a, b, c);
                h = g;
                g = f;
                f = e;
                e = d + T1;
                d = c;
                c = b;
                b = a;
                a = T1 + T2;
            }

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

    } // namespace detail_sha256

    // ================================================================
    // SHA-256
    // ================================================================

    /// SHA-256 ハッシュを計算
    inline std::array<uint8_t, 32> sha256(const uint8_t* data, size_t len) {
        using namespace detail_sha256;

        uint32_t state[8];
        std::memcpy(state, H0, sizeof(state));

        // 完全なブロックを処理
        size_t blocks = len / 64;
        for (size_t i = 0; i < blocks; ++i)
            processBlock(state, data + 64 * i);

        // パディング
        // 残りバイト + 1(0x80) + パディング + 8(長さ) が 64 の倍数になるようにする
        size_t remaining = len % 64;
        uint8_t lastBlocks[128];  // 最大 2 ブロック
        std::memset(lastBlocks, 0, sizeof(lastBlocks));
        std::memcpy(lastBlocks, data + blocks * 64, remaining);
        lastBlocks[remaining] = 0x80;

        size_t padBlocks;
        if (remaining < 56) {
            padBlocks = 1;
        } else {
            padBlocks = 2;
        }

        // メッセージ長 (ビット) を最終 8 バイトに big-endian で格納
        uint64_t bitLen = uint64_t(len) * 8;
        uint8_t* tail = lastBlocks + padBlocks * 64 - 8;
        tail[0] = uint8_t(bitLen >> 56);
        tail[1] = uint8_t(bitLen >> 48);
        tail[2] = uint8_t(bitLen >> 40);
        tail[3] = uint8_t(bitLen >> 32);
        tail[4] = uint8_t(bitLen >> 24);
        tail[5] = uint8_t(bitLen >> 16);
        tail[6] = uint8_t(bitLen >> 8);
        tail[7] = uint8_t(bitLen);

        for (size_t i = 0; i < padBlocks; ++i)
            processBlock(state, lastBlocks + 64 * i);

        // ダイジェスト出力
        std::array<uint8_t, 32> digest;
        for (int i = 0; i < 8; ++i)
            store32be(digest.data() + 4 * i, state[i]);

        return digest;
    }

    /// SHA-256 (文字列入力)
    inline std::array<uint8_t, 32> sha256(const std::string& data) {
        return sha256(reinterpret_cast<const uint8_t*>(data.data()), data.size());
    }

    /// SHA-256 ハッシュを 16 進数文字列で返す
    inline std::string sha256hex(const std::string& data) {
        auto digest = sha256(data);
        static constexpr char hex[] = "0123456789abcdef";
        std::string result;
        result.reserve(64);
        for (uint8_t b : digest) {
            result += hex[b >> 4];
            result += hex[b & 0x0f];
        }
        return result;
    }

    // ================================================================
    // HMAC-SHA256
    // ================================================================

    /// HMAC-SHA256 (RFC 2104)
    inline std::array<uint8_t, 32> hmacSha256(const uint8_t* key, size_t keyLen,
                                               const uint8_t* data, size_t dataLen) {
        constexpr size_t blockSize = 64;   // SHA-256 ブロック長
        constexpr size_t hashSize  = 32;

        // 鍵の正規化: blockSize より長ければハッシュする
        uint8_t keyBlock[blockSize];
        std::memset(keyBlock, 0, blockSize);

        if (keyLen > blockSize) {
            auto hashed = sha256(key, keyLen);
            std::memcpy(keyBlock, hashed.data(), hashSize);
        } else {
            std::memcpy(keyBlock, key, keyLen);
        }

        // ipad = key XOR 0x36, opad = key XOR 0x5c
        uint8_t ipad[blockSize];
        uint8_t opad[blockSize];
        for (size_t i = 0; i < blockSize; ++i) {
            ipad[i] = keyBlock[i] ^ 0x36;
            opad[i] = keyBlock[i] ^ 0x5c;
        }

        // 内側ハッシュ: SHA256(ipad || data)
        std::vector<uint8_t> innerInput(blockSize + dataLen);
        std::memcpy(innerInput.data(), ipad, blockSize);
        std::memcpy(innerInput.data() + blockSize, data, dataLen);
        auto innerHash = sha256(innerInput.data(), innerInput.size());

        // 外側ハッシュ: SHA256(opad || innerHash)
        uint8_t outerInput[blockSize + hashSize];
        std::memcpy(outerInput, opad, blockSize);
        std::memcpy(outerInput + blockSize, innerHash.data(), hashSize);

        return sha256(outerInput, blockSize + hashSize);
    }

} // namespace calx::crypto

#endif // CALX_CRYPTO_HASH_HPP
