/*************************************************
* OpenSSL Reducer Source File                    *
* (C) 1999-2005 The Botan Project                *
*************************************************/

#include <botan/eng_ossl.h>
#include <botan/bn_wrap.h>
#include <openssl/opensslv.h>

#if OPENSSL_VERSION_NUMBER < 0x0090700F
  #error Your OpenSSL install is too old, upgrade to 0.9.7 or later
#endif

namespace Botan {

namespace {

/*************************************************
* OpenSSL Reducer                                *
*************************************************/
class OpenSSL_Reducer : public ModularReducer
   {
   public:
      BigInt multiply(const BigInt&, const BigInt&) const;
      BigInt square(const BigInt&) const;
      BigInt reduce(const BigInt&) const;

      OpenSSL_Reducer(const BigInt& mod) : ModularReducer(mod), n(mod) {}
   private:
      OSSL_BN n;
      OSSL_BN_CTX ctx;
   };

/*************************************************
* Modular Multiplication                         *
*************************************************/
BigInt OpenSSL_Reducer::multiply(const BigInt& x_bn, const BigInt& y_bn) const
   {
   OSSL_BN x(x_bn), y(y_bn);

   BN_mod_mul(x.value, x.value, y.value, n.value, ctx.value);

   if((x_bn.sign() != y_bn.sign()) && !BN_is_zero(x.value))
      BN_sub(x.value, n.value, x.value);

   return x.to_bigint();
   }

/*************************************************
* Modular Squaring                               *
*************************************************/
BigInt OpenSSL_Reducer::square(const BigInt& x_bn) const
   {
   OSSL_BN x(x_bn), r;
   BN_mod_sqr(r.value, x.value, n.value, ctx.value);
   return r.to_bigint();
   }

/*************************************************
* Modular Reduction                              *
*************************************************/
BigInt OpenSSL_Reducer::reduce(const BigInt& x_bn) const
   {
   OSSL_BN x(x_bn), r;
   BN_nnmod(r.value, x.value, n.value, ctx.value);

   if((x_bn.is_negative()) && !BN_is_zero(r.value))
      BN_sub(r.value, n.value, r.value);
   return r.to_bigint();
   }

}

/*************************************************
* Acquire a ModularReducer                       *
*************************************************/
ModularReducer* OpenSSL_Engine::reducer(const BigInt& n, bool) const
   {
   return new OpenSSL_Reducer(n);
   }

}
