#include "libopgp.h"
#include <rand.h>

#define BSZ 8
#define BITSIZ 9
/*------------------------------------*/
void PGP_cenc(FILE * inf, FILE * outf, void *cfbdat)
{
  u8_t dbuf[(1 << BITSIZ) + 20], *bp;
  int j, k;

  fputc(0xc9, outf);            /* conventional encryption packet */
  bp = &dbuf[1];                /* special PGP iv header */
  dbuf[0] = 0xe0 + BITSIZ;
  RAND_bytes(bp, 8);
  bp[8] = bp[6], bp[9] = bp[7];
  PGP_cblk(bp, 10, cfbdat);
  PGP_cres(&bp[10 - BSZ], cfbdat);  /* PGP cfb reset */
  bp += 10;
  j = 10;
  for (;;) {                    /* packetize and encrypt */
    if (0 > (k = fread(bp, 1, (1 << BITSIZ) - j, inf)))
      exit(-2);
    PGP_cblk(bp, k, cfbdat);
    j += k;
    if (j != (1 << BITSIZ))
      break;
    fwrite(dbuf, 1, (1 << BITSIZ) + 1, outf);
    j = 0;
    bp = &dbuf[1];
  }
  if (j > 192) {
    fputc(0xc0 | ((j - 192) >> 8), outf);
    dbuf[0] = j - 192;
  } else
    dbuf[0] = j;
  fwrite(dbuf, 1, j + 1, outf);
  free(cfbdat);
}
