// ---------------------------------------------------------------------------
// - BlockCipher.cpp                                                         -
// - afnix:sec module - block cipher class implementation                    -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  is  distributed in  the hope  that it will be useful, but -
// - without  any  warranty;  without  even   the   implied    warranty   of -
// - merchantability or fitness for a particular purpose.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Item.hpp"
#include "Ascii.hpp"
#include "Vector.hpp"
#include "Unicode.hpp"
#include "Utility.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "BlockCipher.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------

  // this procedure computes a block padding: bit padding
  static bool bc_pad_bitm (t_byte* bi, const long bisz, const long size) {
    // compute the padding count
    long pcnt = bisz - size;
    if (pcnt > 0) {
      // pad the first byte
      bi[size] = 0x80;
      // pad with the serie 80 00 00 00 ...
      for (long i = size+1; i < bisz; i++) bi[i] = 0x00;
      // mark as padded
      return true;
    }
    return false;
  }

  // this procedure compute the next block padding: bit padding
  static bool bc_nxp_bitm (t_byte* bi, const long bisz) {
    // pad the first byte
    bi[0] = 0x80;
    // pad the rest of the block
    for (long i = 1; i < bisz; i++) bi[i] = 0x00;
    // mark as padded
    return true;
  }

  // this procedure computes the number of valid bytes: bit padding
  static long bc_unp_bitm (const t_byte* bo, const long bosz) {
    long pidx = 0;
    for (long i = bosz-1; i >= 0; i--) {
      if (bo[i] == 0x80) {
	pidx = i;
	break;
      }
      if (bo[i] != 0x00) {
	throw Exception ("cipher-error", "invalid padded block");
      }
    }
    // check padded index
    if (bo[pidx] != 0x80) {
      throw Exception ("cipher-error", "invalid padded block");
    }
    // the size if the previous byte index + 1, so is pidx
    return pidx;
  }

  // this procedure computes a block padding: ANSI X.923
  static bool bc_pad_ansi (t_byte* bi, const long bisz, const long size) {
    // compute the padding count
    long pcnt = bisz - size;
    // check the padding
    if (pcnt > 256) {
      throw Exception ("cipher-error", "padding size is too long");
    }
    if (pcnt > 0) {
      // pad with the pad size
      for (long i = size; i < bisz-1; i++) bi[i] = 0x00;
      bi[bisz-1] = (t_byte) pcnt;
      // mark as padded
      return true;
    }
    return false;
  }

  // this procedure computes the next block padding: ANSI X.923
  static bool bc_nxp_ansi (t_byte* bi, const long bisz) {
    // check block size
    if (bisz > 256) {
      throw Exception ("cipher-error", "padding size is too long");
    }
    // pad with the block size
    for (long i = 0; i < bisz-1; i++) bi[i] = 0x00;
    bi[bisz-1] = (t_byte) bisz;
    // mark as padded
    return true;
  }

  // this procedure computes the number of valid bytes: ANSI X.923
  static long bc_unp_ansi (const t_byte* bo, const long bosz) {
    // initialize result
    long result = bosz;
    // extract valid bytes
    long pad = bo[bosz-1];
    if (pad > bosz) {
      throw Exception ("cipher-error", "block padding is too long");	
    }
    // update counter
    result -= pad;
    // number of valid bytes
    return result;
  }

  // this procedure computes a block padding: NIST 800-38A
  static bool bc_pad_nist (t_byte* bi, const long bisz, const long size) {
    // compute the padding count
    long pcnt = bisz - size;
    // check the padding
    if (pcnt > 256) {
      throw Exception ("cipher-error", "padding size is too long");
    }
    if (pcnt > 0) {
      // pad with the pad size
      for (long i = size; i < bisz; i++) bi[i] = (t_byte) pcnt;
      // mark as padded
      return true;
    }
    return false;
  }

  // this procedure computes the next block padding: NIST 800-38A
  static bool bc_nxp_nist (t_byte* bi, const long bisz) {
    // check block size
    if (bisz > 256) {
      throw Exception ("cipher-error", "padding size is too long");
    }
    // pad with the block size
    for (long i = 0; i < bisz; i++) bi[i] = (t_byte) bisz;
    // mark as padded
    return true;
  }

  // this procedure computes the number of valid bytes: NIST 800-38A
  static long bc_unp_nist (const t_byte* bo, const long bosz) {
    // initialize result
    long result = bosz;
    // extract valid bytes
    long pad = bo[bosz-1];
    if (pad > bosz) {
      throw Exception ("cipher-error", "block padding is too long");	
    }
    // update counter
    result -= pad;
    // number of valid bytes
    return result;
  }

  // this procedure computes a block padding by type
  static bool bc_pad (const BlockCipher::t_pmod pmod,
		      t_byte* bi, const long bisz, const long size) {
    // by default do not pad
    bool result = false;
    // check for valid block
    if ((bi == nilp) || (bisz < 0)) return result;
    // select from the padding mode
    switch (pmod) {
    case BlockCipher::CPM_BITM:
      result = bc_pad_bitm (bi, bisz, size);
      break;
    case BlockCipher::CPM_X923:
      result = bc_pad_ansi (bi, bisz, size);
      break;
    case BlockCipher::CPM_N800:
      result = bc_pad_nist (bi, bisz, size);
      break;
    default:
      result = false;
      break;
    }
    return result;
  }
  
  // this procedure computes the next block padding by type
  static bool bc_nxp (const BlockCipher::t_pmod pmod,
		      t_byte* bi, const long bisz) {
    // by default do not pad
    bool result = false;
    // check for valid block
    if ((bi == nilp) || (bisz < 0)) return result;
    // select from the padding mode
    switch (pmod) {
    case BlockCipher::CPM_BITM:
      result = bc_nxp_bitm (bi, bisz);
      break;
    case BlockCipher::CPM_X923:
      result = bc_nxp_ansi (bi, bisz);
      break;
    case BlockCipher::CPM_N800:
      result = bc_nxp_nist (bi, bisz);
      break;
    default:
      result = false;
      break;
    }
    return result;
  }

  // this procedure unpad a block by type
  static long bc_unp (const BlockCipher::t_pmod pmod,
		      t_byte* bo, const long bosz) {
    // by default do not pad
    long result = 0;
    // check for valid block
    if ((bo == nilp) || (bosz < 0)) return result;
    // select from the padding mode
    switch (pmod) {
    case BlockCipher::CPM_NONE:
      result = bosz;
      break;
    case BlockCipher::CPM_BITM:
      result = bc_unp_bitm (bo, bosz);
      break;
    case BlockCipher::CPM_X923:
      result = bc_unp_ansi (bo, bosz);
      break;
    case BlockCipher::CPM_N800:
      result = bc_unp_nist (bo, bosz);
      break;
    }
    return result;
  }

  // this procedure preset the initial vector
  static t_byte* bc_piv (const long ivsz) {
    if (ivsz <= 0) return nilp;
    t_byte* iv = new t_byte[ivsz];
    for (long i = 0; i < ivsz; i++) iv[i] = Utility::byternd ();
    return iv;
  }

  // this procedure presets the last block
  static void bc_pbl (const BlockCipher::t_cmod cmod,
		      t_byte* bl, const t_byte* iv, const long cbsz) {
    // basic checks
    if ((bl == nilp) || (iv == nilp) || (cbsz <= 0)) return;
    // check for cbc mode
    if (cmod == BlockCipher::CBM_CBCM) {
      for (long i = 0; i < cbsz; i++) bl[i] = iv[i];
    }
    // check for cfb mode
    if (cmod == BlockCipher::CBM_CFBM) {
      for (long i = 0; i < cbsz; i++) bl[i] = iv[i];
    }
    // check for ofb mode
    if (cmod == BlockCipher::CBM_OFBM) {
      for (long i = 0; i < cbsz; i++) bl[i] = iv[i];
    }
  }

  // this procedure preprocess a block in ecb mode
  static void bc_pbi_ecb (const bool eflg,
			  t_byte* bt, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) bt[i] = bi[i];
    } else {
      for (long i = 0; i < cbsz; i++) bt[i] = bi[i];
    }      
  }

  // this procedure preprocess a block in cbc mode
  static void bc_pbi_cbc (const bool eflg,
			  t_byte* bt, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) bt[i] = bi[i] ^ bl[i];
    } else {
      for (long i = 0; i < cbsz; i++) bt[i] = bi[i];
    }
  }

  // this procedure postprocess a block in cbc mode
  static void bc_pbo_cbc (const bool eflg,
			  t_byte* bo, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) bl[i] = bo[i];
    } else {
      for (long i = 0; i < cbsz; i++) {
	bo[i] ^= bl[i];
	bl[i]  = bi[i];
      }
    }
  }

  // this procedure preprocess a block in cfb mode
  static void bc_pbi_cfb (const bool eflg,
			  t_byte* bt, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) bt[i] = bl[i];
    } else {
      for (long i = 0; i < cbsz; i++) bt[i] = bl[i];
    }
  }

  // this procedure postprocess a block in cfb mode
  static void bc_pbo_cfb (const bool eflg,
			  t_byte* bo, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) {
	bo[i] ^= bi[i];
	bl[i]  = bo[i];
      }
    } else {
      for (long i = 0; i < cbsz; i++) {
	bo[i] ^= bi[i];
	bl[i]  = bi[i];
      }
    }
  }

  // this procedure preprocess a block in ofb mode
  static void bc_pbi_ofb (const bool eflg,
			  t_byte* bt, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) bt[i] = bl[i];
    } else {
      for (long i = 0; i < cbsz; i++) bt[i] = bl[i];
    }
  }

  // this procedure postprocess a block in ofb mode
  static void bc_pbo_ofb (const bool eflg,
			  t_byte* bo, t_byte* bi, t_byte* bl, const long cbsz) {
    if (eflg == true) {
      for (long i = 0; i < cbsz; i++) {
	bl[i]  = bo[i];
	bo[i] ^= bi[i];
      }
    } else {
      for (long i = 0; i < cbsz; i++) {
	bl[i]  = bo[i];
	bo[i] ^= bi[i];
      }
    }
  }

  // this procedure preprocess a block cipher mode
  static void bc_pbi (const BlockCipher::t_cmod cmod, const bool eflg,
		      t_byte* bt, t_byte* bi, t_byte* bl, const long cbsz) {
    // check for valid block
    if ((bt == nilp) || (bi == nilp) ||	(bl == nilp) || (cbsz < 0)) return;
    // process the block mode
    switch (cmod) {
    case BlockCipher::CBM_ECBM:
      bc_pbi_ecb (eflg, bt, bi, bl, cbsz);
      break;
    case BlockCipher::CBM_CBCM:
      bc_pbi_cbc (eflg, bt, bi, bl, cbsz);
      break;
    case BlockCipher::CBM_CFBM:
      bc_pbi_cfb (eflg, bt, bi, bl, cbsz);
      break;
    case BlockCipher::CBM_OFBM:
      bc_pbi_ofb (eflg, bt, bi, bl, cbsz);
      break;
    }
  }

  // this procedure postprocess a block cipher mode
  static void bc_pbo (const BlockCipher::t_cmod cmod, const bool eflg,
		      t_byte* bo, t_byte* bi, t_byte* bl, const long cbsz) {
    // check for valid block
    if ((bo == nilp) || (bi == nilp) ||	(bl == nilp) || (cbsz < 0)) return;
    // process the block mode
    switch (cmod) {
    case BlockCipher::CBM_ECBM:
      break;
    case BlockCipher::CBM_CBCM:
      bc_pbo_cbc (eflg, bo, bi, bl, cbsz);
      break;
    case BlockCipher::CBM_CFBM:
      bc_pbo_cfb (eflg, bo, bi, bl, cbsz);
      break;
    case BlockCipher::CBM_OFBM:
      bc_pbo_ofb (eflg, bo, bi, bl, cbsz);
      break;
    }
  }

  // this procedure returns true for mode encoding
  static bool bc_bme (const BlockCipher::t_cmod cmod) {
    bool result = true;
    switch (cmod) {
    case BlockCipher::CBM_ECBM:
    case BlockCipher::CBM_CBCM:
    case BlockCipher::CBM_OFBM:
    case BlockCipher::CBM_CFBM:
      break;
    }
    return result;
  }

  // this procedure returns true for mode decoding
  static bool bc_bmd (const BlockCipher::t_cmod cmod) {
    bool result = true;
    switch (cmod) {
    case BlockCipher::CBM_ECBM:
    case BlockCipher::CBM_CBCM:
      break;
    case BlockCipher::CBM_OFBM:
    case BlockCipher::CBM_CFBM:
      result = false;
      break;
    }
    return result;
  }
 
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a block cipher by key

  BlockCipher::BlockCipher (const String& name, 
			    const long cbsz) : Cipher (name) {
    // check the cipher size
    if (cbsz <= 0) {
      throw Exception ("cipher-error", "invalid cipher block size");
    }
    // set the cipher info
    d_cbsz = cbsz;
    d_pmod = CPM_N800;
    d_cmod = CBM_ECBM;
    // create the byte blocks
    p_bl = new t_byte[d_cbsz];
    // preset initial vector
    p_iv = bc_piv (d_cbsz);
    // reset eveything
    reset ();
  }

  // destroy this block cipher

  BlockCipher::~BlockCipher (void) {
    delete [] p_bl;
    delete [] p_iv;
  }

  // return the class name

  String BlockCipher::repr (void) const {
    return "BlockCipher";
  }

  // reset the block cipher

  void BlockCipher::reset (void) {
    wrlock ();
    try {
      // reset the last block
      for (long i = 0; i < d_cbsz; i++) p_bl[i] = nilc;
      // set the last block with the initial vector
      bc_pbl (d_cmod, p_bl, p_iv, d_cbsz);
      // done
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }


  // set the block cipher key

  void BlockCipher::setkey (const Key& key) {
    wrlock ();
    try {
      // check the key for validity
      if (key.isbk () == false) {
	throw Exception ("cipher-error", "invalid key for block cipher");
      } 
      // set the key and return
      Cipher::setkey (key);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the normal waist from a file size

  t_long BlockCipher::waist (const t_long size) const {
    rdlock ();
    try {
      // compute the initial size
      t_long result = (size / d_cbsz) * d_cbsz;
      if ((size == 0) || ((size % d_cbsz) != 0)) result+= d_cbsz;
      // eventually add a padding block
      switch (d_pmod) {
      case CPM_BITM:
      case CPM_X923:
      case CPM_N800:
	if ((size > 0) && ((size % d_cbsz) == 0)) result += d_cbsz;
	break;
      default:
	break;
      }
      // eventually add a cipher mode block
      switch (d_cmod) {
      case CBM_CBCM:
      case CBM_CFBM:
      case CBM_OFBM:
	if (result > 0) result += d_cbsz;
	break;
      default:
	break;
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // encode an input buffer into an output buffer

  long BlockCipher::encode (Buffer& ob, Buffer& ib) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (ib.empty () == true)) {
	unlock ();
	return 0;
      }
      // initialize the local buffers
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (ib.empty () == true) break;
	bi[cc++] = ib.read ();
      }
      // fill in the last byte
      for (long i = cc; i < d_cbsz; i++) bi[i] = nilc;
      // check for padding
      bool padf = (cc < d_cbsz) ? bc_pad (d_pmod, bi, d_cbsz, cc) : false;
      // preprocess the block mode
      bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
      // encode the block
      bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
      // update the output buffer
      ob.add ((char*) bo, d_cbsz);
      // check for extra padded block
      if ((padf == false) && (ib.empty () == true)) {
	// fill next pad block
	bool pnxf =  bc_nxp (d_pmod, bi, d_cbsz);
	// add it in the buffer
	if (pnxf == true) {
	  // preprocess the block mode
	  bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
	  // encode the block
	  bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
	  // postprocess the block mode
	  bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
	  // update the output buffer
	  ob.add ((char*) bo, d_cbsz);
	}
      }
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // encode an input stream into an output buffer

  long BlockCipher::encode (Buffer& ob, InputStream& is) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (is.valid () == false)) {
	unlock ();
	return 0;
      }
      // initialize the local buffers
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (is.valid () == false) break;
	bi[cc++] = is.read ();
      }
      // fill in the last byte
      for (long i = cc; i < d_cbsz; i++) bi[i] = nilc;
      // check for padding
      bool padf = (cc < d_cbsz) ? bc_pad (d_pmod, bi, d_cbsz, cc) : false;
      // preprocess the block mode
      bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
      // encode the block
      bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
      // update the output stream
      ob.add ((char*) bo, d_cbsz);
      // check for extra padded block
      if ((padf == false) && (is.valid () == false)) {
	// fill next pad block
	bool pnxf =  bc_nxp (d_pmod, bi, d_cbsz);
	// add it in the buffer
	if (pnxf == true) {
	  // preprocess the block mode
	  bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
	  // encode the block
	  bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
	  // postprocess the block mode
	  bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
	  // update the output stream
	  ob.add ((char*) bo, d_cbsz);
	}
      }
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // encode an input stream into an output stream

  long BlockCipher::encode (OutputStream& os, InputStream& is) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (is.valid () == false)) {
	unlock ();
	return 0;
      }
      // initialize the local buffers
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (is.valid () == false) break;
	bi[cc++] = is.read ();
      }
      // fill in the last byte
      for (long i = cc; i < d_cbsz; i++) bi[i] = nilc;
      // check for padding
      bool padf = (cc < d_cbsz) ? bc_pad (d_pmod, bi, d_cbsz, cc) : false;
      // preprocess the block mode
      bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
      // encode the block
      bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
      // update the output stream
      os.write ((char*) bo, d_cbsz);
      // check for extra padded block
      if ((padf == false) && (is.valid () == false)) {
	// fill next pad block
	bool pnxf =  bc_nxp (d_pmod, bi, d_cbsz);
	// add it in the buffer
	if (pnxf == true) {
	  // preprocess the block mode
	  bc_pbi (d_cmod, true, bt, bi, p_bl, d_cbsz);
	  // encode the block
	  bc_bme (d_cmod) ? encode (bo, bt) : decode (bo, bt);
	  // postprocess the block mode
	  bc_pbo (d_cmod, true, bo, bi, p_bl, d_cbsz);
	  // update the output stream
	  os.write ((char*) bo, d_cbsz);
	}
      }
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // decode an input buffer into an output buffer

  long BlockCipher::decode (Buffer& ob, Buffer& ib) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (ib.empty () == true)) {
	unlock ();
	return 0;
      }
      // initialize the local buffer
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (ib.empty () == true) break;
	bi[cc++] = ib.read ();
      }
      // check the block size
      if (cc != d_cbsz) {
	throw Exception ("cipher-error", "invalid block size to decode");
      }
      // preprocess the block mode
      bc_pbi (d_cmod, false, bt, bi, p_bl, d_cbsz);
      // decode the block
      bc_bmd (d_cmod) ? decode (bo, bt) : encode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, false, bo, bi, p_bl, d_cbsz);
      // check for last block unpadding
      if (ib.empty () == true) {
	cc = bc_unp (d_pmod, bo, d_cbsz);
      }
      // update the output buffer
      if (cc > 0) ob.add ((char*) bo, cc);
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // decode an input stream into an output buffer

  long BlockCipher::decode (Buffer& ob, InputStream& is) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (is.valid () == false)) {
	unlock ();
	return 0;
      }
      // initialize the local buffer
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (is.valid () == false) break;
	bi[cc++] = is.read ();
      }
      // check the block size
      if (cc != d_cbsz) {
	throw Exception ("cipher-error", "invalid block size to decode");
      }
      // preprocess the block mode
      bc_pbi (d_cmod, false, bt, bi, p_bl, d_cbsz);
      // decode the block
      bc_bmd (d_cmod) ? decode (bo, bt) : encode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, false, bo, bi, p_bl, d_cbsz);
      // check for last block unpadding
      if (is.valid () == false) {
	cc = bc_unp (d_pmod, bo, d_cbsz);
      }
      // update the output buffer
      if (cc > 0) ob.add ((char*) bo, cc);
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // decode an input stream into an output stream

  long BlockCipher::decode (OutputStream& os, InputStream& is) {
    wrlock ();
    try {
      // check the block size
      if ((d_cbsz == 0) || (is.valid () == false)) {
	unlock ();
	return 0;
      }
      // initialize the local buffer
      t_byte bi[d_cbsz];
      t_byte bo[d_cbsz];
      t_byte bt[d_cbsz];
      // initialize the input buffer
      long cc = 0;
      for (long i = 0; i < d_cbsz; i++) {
	if (is.valid () == false) break;
	bi[cc++] = is.read ();
      }
      // check the block size
      if (cc != d_cbsz) {
	throw Exception ("cipher-error", "invalid block size to decode");
      }
      // preprocess the block mode
      bc_pbi (d_cmod, false, bt, bi, p_bl, d_cbsz);
      // decode the block
      bc_bmd (d_cmod) ? decode (bo, bt) : encode (bo, bt);
      // postprocess the block mode
      bc_pbo (d_cmod, false, bo, bi, p_bl, d_cbsz);
      // check for last block unpadding
      if (is.valid () == false) {
	cc = bc_unp (d_pmod, bo, d_cbsz);
      }
      // update the output buffer
      if (cc > 0) os.write ((char*) bo, cc);
      unlock ();
      return cc;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the cipher block size

  long BlockCipher::getcbsz (void) const {
    rdlock ();
    try {
      long result = d_cbsz;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the block cipher padding mode

  void BlockCipher::setpmod (const t_pmod pmod) {
    wrlock ();
    try {
      d_pmod = pmod;
      reset  ();
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the block cipher padding mode

  BlockCipher::t_pmod BlockCipher::getpmod (void) const {
    rdlock ();
    try {
      t_pmod result = d_pmod;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the block cipher mode

  void BlockCipher::setcmod (const t_cmod cmod) {
    wrlock ();
    try {
      d_cmod = cmod;
      reset  ();
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the block cipher mode

  BlockCipher::t_cmod BlockCipher::getcmod (void) const {
    rdlock ();
    try {
      t_cmod result = d_cmod;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

 void BlockCipher::setiv (const String& ivs) {
    // convert the octet string
    long ivsz = 0;
    t_byte* sbuf = Unicode::stob (ivsz, ivs);
    // lock and set
    wrlock ();
    try {
      for (long i = 0; i < d_cbsz; i++) p_iv[i] = sbuf[i];
      delete [] sbuf;
      reset  ();
      unlock ();
    } catch (...) {
      delete [] sbuf;
      unlock ();
      throw;
    }
  }

  // get the initial vector buffer

  String BlockCipher::getiv (void) const {
    rdlock ();
    try {
      String result = Ascii::btos (p_iv, d_cbsz);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the object eval quarks
  static const long QUARK_NONE    = String::intern ("PAD-NONE");
  static const long QUARK_BITM    = String::intern ("PAD-BIT-MODE");
  static const long QUARK_X923    = String::intern ("PAD-ANSI-X923");
  static const long QUARK_N800    = String::intern ("PAD-NIST-800");
  static const long QUARK_ECBM    = String::intern ("MODE-ECB");
  static const long QUARK_CBCM    = String::intern ("MODE-CBC");
  static const long QUARK_CFBM    = String::intern ("MODE-CFB");
  static const long QUARK_OFBM    = String::intern ("MODE-OFB");
  static const long QUARK_BCIPHER = String::intern ("BlockCipher");

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 8;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_WAIST   = zone.intern ("waist");
  static const long QUARK_SETIV   = zone.intern ("set-iv");
  static const long QUARK_GETIV   = zone.intern ("get-iv");
  static const long QUARK_GETCBSZ = zone.intern ("get-block-size");
  static const long QUARK_SETCMOD = zone.intern ("set-block-mode");
  static const long QUARK_GETCMOD = zone.intern ("get-block-mode");
  static const long QUARK_SETPMOD = zone.intern ("set-padding-mode");
  static const long QUARK_GETPMOD = zone.intern ("get-padding-mode");

  // map an enumeration item to a block cipher padding mode
  static inline BlockCipher::t_pmod item_to_pmod (const Item& item) {
    // check for an input cipher item
    if (item.gettid () != QUARK_BCIPHER)
      throw Exception ("item-error", "item is not a block cipher item");
    // map the item to the enumeration
    long quark = item.getquark ();
    if (quark == QUARK_NONE) return BlockCipher::CPM_NONE;
    if (quark == QUARK_BITM) return BlockCipher::CPM_BITM;
    if (quark == QUARK_X923) return BlockCipher::CPM_X923;
    if (quark == QUARK_N800) return BlockCipher::CPM_N800;
    throw Exception ("item-error",
                     "cannot map item to block cipher padding mode");
  }

  // map an enumeration item to a block cipher mode
  static inline BlockCipher::t_cmod item_to_cmod (const Item& item) {
    // check for an input cipher item
    if (item.gettid () != QUARK_BCIPHER)
      throw Exception ("item-error", "item is not a block cipher item");
    // map the item to the enumeration
    long quark = item.getquark ();
    if (quark == QUARK_ECBM) return BlockCipher::CBM_ECBM;
    if (quark == QUARK_CBCM) return BlockCipher::CBM_CBCM;
    if (quark == QUARK_CFBM) return BlockCipher::CBM_CFBM;
    if (quark == QUARK_OFBM) return BlockCipher::CBM_OFBM;
    throw Exception ("item-error",
                     "cannot map item to block cipher mode");
  }

  // map a block cipher padding mode to an item
  static inline Item* pmod_to_item (const BlockCipher::t_pmod pmod) {
    switch (pmod) {
    case BlockCipher::CPM_NONE:
      return new Item (QUARK_BCIPHER, QUARK_NONE);
      break;
    case BlockCipher::CPM_BITM:
      return new Item (QUARK_BCIPHER, QUARK_BITM);
      break;
    case BlockCipher::CPM_X923:
      return new Item (QUARK_BCIPHER, QUARK_X923);
      break;
    case BlockCipher::CPM_N800:
      return new Item (QUARK_BCIPHER, QUARK_N800);
      break;
    }
    return nilp;
  }

  // map a block cipher mode to an item
  static inline Item* cmod_to_item (const BlockCipher::t_cmod cmod) {
    switch (cmod) {
    case BlockCipher::CBM_ECBM:
      return new Item (QUARK_BCIPHER, QUARK_ECBM);
      break;
    case BlockCipher::CBM_CBCM:
      return new Item (QUARK_BCIPHER, QUARK_CBCM);
      break;
    case BlockCipher::CBM_CFBM:
      return new Item (QUARK_BCIPHER, QUARK_CFBM);
      break;
    case BlockCipher::CBM_OFBM:
      return new Item (QUARK_BCIPHER, QUARK_OFBM);
      break;
    }
    return nilp;
  }

  // evaluate an object data member

  Object* BlockCipher::meval (Runnable* robj, Nameset* nset,
			      const long quark) {
    if (quark == QUARK_NONE)
      return new Item (QUARK_BCIPHER, QUARK_NONE);
    if (quark == QUARK_BITM)
      return new Item (QUARK_BCIPHER, QUARK_BITM);
    if (quark == QUARK_X923)
      return new Item (QUARK_BCIPHER, QUARK_X923);
    if (quark == QUARK_N800)
      return new Item (QUARK_BCIPHER, QUARK_N800);
    if (quark == QUARK_ECBM)
      return new Item (QUARK_BCIPHER, QUARK_ECBM);
    if (quark == QUARK_CBCM)
      return new Item (QUARK_BCIPHER, QUARK_CBCM);
    if (quark == QUARK_CFBM)
      return new Item (QUARK_BCIPHER, QUARK_CFBM);
    if (quark == QUARK_OFBM)
      return new Item (QUARK_BCIPHER, QUARK_OFBM);
    throw Exception ("eval-error", "cannot evaluate member",
                     String::qmap (quark));
  }

  // return true if the given quark is defined

  bool BlockCipher::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Cipher::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this object with a set of arguments and a quark
  
  Object* BlockCipher::apply (Runnable* robj, Nameset* nset, const long quark,
			      Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_GETIV)   return new String (getiv ());
      if (quark == QUARK_GETPMOD) return pmod_to_item (getpmod ());
      if (quark == QUARK_GETCMOD) return cmod_to_item (getcmod ());
      if (quark == QUARK_GETCBSZ) return new Integer  (getcbsz ());
    }
    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_SETIV) {
	String iv = argv->getstring (0);
	setiv (iv);
	return nilp;
      }
      if (quark == QUARK_SETPMOD) {
        Object* obj = argv->get (0);
        Item*  iobj = dynamic_cast <Item*> (obj);
        if (iobj == nilp) {
          throw Exception ("type-error", "invalid object with set padding mode",
                           Object::repr (obj));
        }
        t_pmod pmod = item_to_pmod (*iobj);
        setpmod (pmod);
        return nilp;
      }
      if (quark == QUARK_SETCMOD) {
        Object* obj = argv->get (0);
        Item*  iobj = dynamic_cast <Item*> (obj);
        if (iobj == nilp) {
          throw Exception ("type-error", "invalid object with set mode",
                           Object::repr (obj));
        }
        t_cmod cmod = item_to_cmod (*iobj);
        setcmod (cmod);
        return nilp;
      }
      if (quark == QUARK_WAIST) {
	t_long size = argv->getlong (0);
	return new Integer (waist (size));
      }
    }
    // call the cipher method
    return Cipher::apply (robj, nset, quark, argv);
  }
}
