/* Copyright (c) 2026 Jakub Juszczakiewicz
 * All rights reserved.
 */

#include <rsa.h>
#include <string.h>
#include <random.h>

#define TEST_BITS 1024

const char data_in[TEST_BITS / 8 - 1] =
  { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
const size_t data_in_len = sizeof(data_in);

int test_rsa_works(void)
{
  struct RSA * rsa = rsa_new(TEST_BITS);
  char data_out_1[TEST_BITS / 8 + 16];
  char data_out_2[TEST_BITS / 8 + 16];

  size_t len = rsa_enc_pub(rsa, data_in, data_in_len, data_out_1);
  len = rsa_dec_prv(rsa, data_out_1, len, data_out_2);

  if (len != data_in_len) {
    rsa_done(rsa);
    return 1;
  }

  if (memcmp(data_in, data_out_2, len) != 0) {
    rsa_done(rsa);
    return 1;
  }

  rsa_done(rsa);

  return 0;
}

int test_rsa_process_works(void)
{
  struct RSA * rsa = rsa_new(TEST_BITS);
  char data_out_1[TEST_BITS / 4 + 16];
  char data_out_2[TEST_BITS / 4 + 16];

  size_t len = rsa_process_out(rsa, 1, data_in, data_in_len, data_out_1);
  len = rsa_process_in(rsa, 0, data_out_1, len, data_out_2);

  if (len != data_in_len) {
    rsa_done(rsa);
    return 1;
  }

  if (memcmp(data_in, data_out_2, len) != 0) {
    rsa_done(rsa);
    return 1;
  }

  rsa_done(rsa);

  return 0;
}

int main(void)
{
  random_init();
  int r;

  r = test_rsa_works();
  if (r) {
    random_done();
    return r;
  }

  r = test_rsa_process_works();
  if (r) {
    random_done();
    return r;
  }

  random_done();
  return 0;
}
