/*
 * Copyright (c) 2024, stelar7  <dudedbz@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCrypto/Hash/MGF.h>
#include <LibCrypto/Hash/SHA1.h>
#include <LibCrypto/Hash/SHA2.h>
#include <LibCrypto/Padding/OAEP.h>
#include <LibTest/TestCase.h>

// https://www.inf.pucrs.br/~calazans/graduate/TPVLSI_I/RSA-oaep_spec.pdf
TEST_CASE(test_oaep)
{
    u8 message_raw[16] {
        0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49
    };
    auto message = ReadonlyBytes { message_raw, 16 };

    u8 params_raw[0] {};
    auto params = ReadonlyBytes { params_raw, 0 };

    u8 expected_raw[127] {
        0xeb, 0x7a, 0x19, 0xac, 0xe9, 0xe3, 0x00, 0x63,
        0x50, 0xe3, 0x29, 0x50, 0x4b, 0x45, 0xe2, 0xca,
        0x82, 0x31, 0x0b, 0x26, 0xdc, 0xd8, 0x7d, 0x5c,
        0x68, 0xf1, 0xee, 0xa8, 0xf5, 0x52, 0x67, 0xc3,
        0x1b, 0x2e, 0x8b, 0xb4, 0x25, 0x1f, 0x84, 0xd7,
        0xe0, 0xb2, 0xc0, 0x46, 0x26, 0xf5, 0xaf, 0xf9,
        0x3e, 0xdc, 0xfb, 0x25, 0xc9, 0xc2, 0xb3, 0xff,
        0x8a, 0xe1, 0x0e, 0x83, 0x9a, 0x2d, 0xdb, 0x4c,
        0xdc, 0xfe, 0x4f, 0xf4, 0x77, 0x28, 0xb4, 0xa1,
        0xb7, 0xc1, 0x36, 0x2b, 0xaa, 0xd2, 0x9a, 0xb4,
        0x8d, 0x28, 0x69, 0xd5, 0x02, 0x41, 0x21, 0x43,
        0x58, 0x11, 0x59, 0x1b, 0xe3, 0x92, 0xf9, 0x82,
        0xfb, 0x3e, 0x87, 0xd0, 0x95, 0xae, 0xb4, 0x04,
        0x48, 0xdb, 0x97, 0x2f, 0x3a, 0xc1, 0x4f, 0x7b,
        0xc2, 0x75, 0x19, 0x52, 0x81, 0xce, 0x32, 0xd2,
        0xf1, 0xb7, 0x6d, 0x4d, 0x35, 0x3e, 0x2d
    };
    auto expected = ReadonlyBytes { expected_raw, 127 };

    u8 seed_data[20] {
        0xaa, 0xfd, 0x12, 0xf6, 0x59, 0xca, 0xe6, 0x34,
        0x89, 0xb4, 0x79, 0xe5, 0x07, 0x6d, 0xde, 0xc2,
        0xf0, 0x6c, 0xb5, 0x8f
    };

    auto maybe_result = Crypto::Padding::OAEP::encode<Crypto::Hash::SHA1, Crypto::Hash::MGF>(
        message,
        params,
        127,
        [&](auto buffer) {
            memcpy(buffer.data(), seed_data, 20);
        });
    auto result = maybe_result.release_value();

    EXPECT_EQ(expected, result);
}
