/*************************************************
* Rabin-Williams Source File                     *
* (C) 1999-2003 The Botan Project                *
*************************************************/

#include <botan/rw.h>
#include <botan/numthry.h>
#include <botan/keypair.h>

namespace Botan {

/*************************************************
* RW_PublicKey Constructor                       *
*************************************************/
RW_PublicKey::RW_PublicKey(const BigInt& mod, const BigInt& exp)
   {
   if_initialize(mod, exp, false);
   }

/*************************************************
* Rabin-Williams Public Operation                *
*************************************************/
BigInt RW_PublicKey::public_op(const BigInt& i) const
   {
   if(i > n / 2 || i.is_negative())
      throw Invalid_Argument(algo_name() + "::public_op: i > n / 2 || i < 0");

   BigInt t1 = powermod_e_n(i);
   if(t1 % 16 == 12) return t1;
   if(t1 % 8 == 6)   return 2*t1;

   BigInt t2 = n - t1;
   if(t2 % 16 == 12) return t2;
   if(t2 % 8 == 6)   return 2*t2;

   throw Invalid_Argument(algo_name() + "::public_op: Invalid input");
   }

/*************************************************
* Rabin-Williams Verification Function           *
*************************************************/
SecureVector<byte> RW_PublicKey::verify(const byte in[], u32bit len) const
   {
   BigInt temp(in, len);
   return BigInt::encode(public_op(temp));
   }

/*************************************************
* Return the name of this algorithm              *
*************************************************/
std::string RW_PublicKey::algo_name() const
   {
   return "RW";
   }

/*************************************************
* RW_PrivateKey Constructor                      *
*************************************************/
RW_PrivateKey::RW_PrivateKey(const BigInt& prime1, const BigInt& prime2,
                             const BigInt& exp, const BigInt& d_exp,
                             const BigInt& modulus) :
   RW_PublicKey(((!modulus) ? prime1 * prime2 : modulus), exp)
   {
   if(prime1 < 3 || prime2 < 3 || (d_exp != 0 && d_exp < 3))
      throw Invalid_Argument(algo_name() + ": Invalid private key");

   p = prime1;
   q = prime2;
   d = (!d_exp) ? inverse_mod(e, lcm(p - 1, q - 1) / 2) : d_exp;
   precompute();
   }

/*************************************************
* Create a Rabin-Williams private key            *
*************************************************/
RW_PrivateKey::RW_PrivateKey(u32bit bits, u32bit exp)
   {
   if(bits < 512)
      throw Invalid_Argument(algo_name() + ": Can't make a key that is only " +
                             to_string(bits) + " bits long");
   if(exp < 2 || exp % 2 == 1)
      throw Invalid_Argument(algo_name() + ": Invalid encryption exponent");

   e = exp;
   p = random_prime((bits + 1) / 2, LongTermKey, e / 2, 3, 4);
   q = random_prime(bits - p.bits(), LongTermKey, e / 2,
                    ((p % 8 == 3) ? 7 : 3), 8);

   n = p * q;
   d = inverse_mod(e, lcm(p - 1, q - 1) / 2);
   precompute();

   if(!check_params())
      throw Self_Test_Failure(algo_name() + " private key generation failed");
   }

/*************************************************
* Rabin-Williams Signature Operation             *
*************************************************/
SecureVector<byte> RW_PrivateKey::sign(const byte in[], u32bit len) const
   {
   BigInt temp(in, len);
   return BigInt::encode_1363(private_op(temp), n.bytes());
   }

/*************************************************
* Rabin-Williams Private Key Operation           *
*************************************************/
BigInt RW_PrivateKey::private_op(const BigInt& i) const
   {
   if(i >= n || i.is_negative())
      throw Invalid_Argument(algo_name() + "::private_op: i >= n || i < 0");
   if(i % 16 != 12)
      throw Invalid_Argument(algo_name() + "::private_op: i % 16 != 12");

   BigInt t;
   if(jacobi(i, n) == 1)
      t = if_private_op(i);
   else
      t = if_private_op(i / 2);

   BigInt result = std::min(t, n - t);
   if(i != public_op(result))
      throw Self_Test_Failure(algo_name() + " private operation check failed");
   return result;
   }

/*************************************************
* Check Private Rabin-Williams Parameters        *
*************************************************/
bool RW_PrivateKey::check_params() const
   {
   if(!IF_Scheme_PrivateKey::check_params())
      return false;
   if((e * d) % (lcm(p - 1, q - 1) / 2) != 1)
      return false;

   try {
      KeyPair::check_key(get_pk_signer(*this, "EMSA2(SHA-1)"),
                         get_pk_verifier(*this, "EMSA2(SHA-1)")
         );
      }
   catch(Self_Test_Failure)
      {
      return false;
      }

   return true;
   }

}
