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

#include <botan/dl_algo.h>
#include <botan/asn1.h>

namespace Botan {

/*************************************************
* DL_Scheme_PublicKey Initializer                *
*************************************************/
void DL_Scheme_PublicKey::dl_initialize(const DL_Group& grp, const BigInt& key)
   {
   group = grp;
   y = key;
   if(y != 0 && (y < 2 || y >= group.get_p()))
      throw Invalid_Argument(algo_name() + ": Invalid public key");
   }

/*************************************************
* Return the X.509 public key encoding           *
*************************************************/
SecureVector<byte> DL_Scheme_PublicKey::DER_encode_pub() const
   {
   DER_Encoder encoder;
   DER::encode(encoder, y);
   return encoder.get_contents();
   }

/*************************************************
* Decode a X.509 public key encoding             *
*************************************************/
void DL_Scheme_PublicKey::BER_decode_pub(DataSource& source)
   {
   BigInt new_y;
   BER_Decoder decoder(source);
   BER::decode(decoder, new_y);
   if(new_y < 2 || new_y >= group.get_p())
      throw Invalid_Argument(algo_name() + ": Invalid public key");
   y = new_y;
   }

/*************************************************
* Check Public DL Parameters                     *
*************************************************/
bool DL_Scheme_PublicKey::check_params() const
   {
   if(y < 2 || y >= group.get_p())
      return false;
   if(!group.verify_group())
      return false;
   return true;
   }

/*************************************************
* Return the PKCS #8 private key encoding        *
*************************************************/
SecureVector<byte> DL_Scheme_PrivateKey::DER_encode_priv() const
   {
   DER_Encoder encoder;
   DER::encode(encoder, x);
   return encoder.get_contents();
   }

/*************************************************
* Decode a PKCS #8 private key encoding          *
*************************************************/
void DL_Scheme_PrivateKey::BER_decode_priv(DataSource& source)
   {
   BigInt new_x;
   BER_Decoder decoder(source);
   BER::decode(decoder, new_x);

   if(new_x <= 0)
      throw Invalid_Argument(algo_name() + ": Invalid private key");
   x = new_x;
   }

}
