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

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

namespace Botan {

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

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

/*************************************************
* RSA Encryption Function                        *
*************************************************/
SecureVector<byte> RSA_PublicKey::encrypt(const byte in[], u32bit len) const
   {
   BigInt temp(in, len);
   return BigInt::encode_1363(public_op(temp), n.bytes());
   }

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

/*************************************************
* RSA Public Operation                           *
*************************************************/
BigInt RSA_PublicKey::public_op(const BigInt& i) const
   {
   if(i >= n || i.is_negative())
      throw Invalid_Argument(algo_name() + "::public_op: i >= n || i < 0");
   return powermod_e_n(i);
   }

/*************************************************
* RSA_PrivateKey Constructor                     *
*************************************************/
RSA_PrivateKey::RSA_PrivateKey(const BigInt& prime1, const BigInt& prime2,
                               const BigInt& exp, const BigInt& d_exp,
                               const BigInt& modulus) :
   RSA_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)) : d_exp;
   precompute();
   }

/*************************************************
* Create a RSA private key                       *
*************************************************/
RSA_PrivateKey::RSA_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 < 3 || exp % 2 == 0)
      throw Invalid_Argument(algo_name() + ": Invalid encryption exponent");

   e = exp;
   p = random_prime((bits + 1) / 2, LongTermKey, e);
   q = random_prime(bits - p.bits(), LongTermKey, e);
   n = p * q;
   d = inverse_mod(e, lcm(p - 1, q - 1));
   precompute();

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

/*************************************************
* RSA Decryption Operation                       *
*************************************************/
SecureVector<byte> RSA_PrivateKey::decrypt(const byte in[], u32bit len) const
   {
   BigInt i(in, len);
   BigInt result = if_private_op(i);
   if(i != powermod_e_n(result))
      throw Self_Test_Failure(algo_name() + " private operation check failed");
   return BigInt::encode(result);
   }

/*************************************************
* RSA Signature Operation                        *
*************************************************/
SecureVector<byte> RSA_PrivateKey::sign(const byte in[], u32bit len) const
   {
   BigInt i(in, len);
   BigInt result = if_private_op(i);
   if(i != powermod_e_n(result))
      throw Self_Test_Failure(algo_name() + " private operation check failed");
   return BigInt::encode_1363(result, n.bytes());
   }

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

   try {
      KeyPair::check_key(get_pk_encryptor(*this, "EME1(SHA-1)"),
                         get_pk_decryptor(*this, "EME1(SHA-1)")
         );

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

   return true;
   }

}
