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

#include <botan/symkey.h>
#include <botan/pipe.h>
#include <botan/hex.h>
#include <botan/rng.h>

namespace Botan {

/*************************************************
* Create an OctetString from RNG output          *
*************************************************/
void OctetString::change(u32bit length, RNG_Quality level)
   {
   bits.create(length);
   Global_RNG::randomize(bits, length, level);
   }

/*************************************************
* Create an OctetString from a hex string        *
*************************************************/
void OctetString::change(const std::string& hex_string)
   {
   SecureVector<byte> hex;
   for(u32bit j = 0; j != hex_string.length(); j++)
      if(Hex_Decoder::is_valid(hex_string[j]))
         hex.append(hex_string[j]);

   if(hex.size() % 2 != 0)
      throw Invalid_Argument("OctetString: hex string must encode full bytes");
   bits.create(hex.size() / 2);
   for(u32bit j = 0; j != bits.size(); j++)
      bits[j] = Hex_Decoder::decode(hex.ptr() + 2*j);
   }

/*************************************************
* Create an OctetString from a byte string       *
*************************************************/
void OctetString::change(const byte in[], u32bit n)
   {
   bits.create(n);
   bits.copy(in, n);
   }

/*************************************************
* Hex encode an OctetString                      *
*************************************************/
std::string OctetString::to_string() const
   {
   Pipe pipe(new Hex_Encoder);
   pipe.process_msg(bits);
   return pipe.read_all_as_string();
   }

/*************************************************
* XOR Operation for OctetStrings                 *
*************************************************/
OctetString& OctetString::operator^=(const OctetString& k)
   {
   if(&k == this) { bits.clear(); return (*this); }
   xor_buf(bits.ptr(), k, std::min(length(), k.length()));
   return (*this);
   }

/*************************************************
* Append Operation for OctetStrings              *
*************************************************/
OctetString operator+(const OctetString& k1, const OctetString& k2)
   {
   SecureVector<byte> ret;
   ret.append(k1, k1.length());
   ret.append(k2, k2.length());
   return OctetString(ret);
   }

/*************************************************
* XOR Operation for OctetStrings                 *
*************************************************/
OctetString operator^(const OctetString& k1, const OctetString& k2)
   {
   SecureVector<byte> ret(std::max(k1.length(), k2.length()));
   ret.copy(k1, k1.length());
   xor_buf(ret, k2, k2.length());
   return OctetString(ret);
   }

}
