#include "libopgp.h"

/*------------------------------------*/
/* string to key and initialize conventional encryption */
int PGP_gts2k(u8_t ** bp, u8_t * passph, void **ccfb)
{
  u32_t i = 0, ic, k = 0;
  u8_t hbuf[256], hkobuf[256], ca, ha, sa, tag;
  VoidHand thand;
  FormPtr renf;
  FieldPtr textf;

  tag = *(*bp)++;               /* application */
  if (tag == 0)
    return 0;

  if( !(renf = FrmInitForm(1000)))
    exit(-1);

  textf = FrmGetObjectPtr(renf, FrmGetObjectIndex(renf, 1002));

  if (2000 == FrmDoDialog(renf)) {
    thand = (VoidHand) FldGetTextHandle(textf);
    passph = MemHandleLock(thand);
  }
  else {
    FrmDeleteForm(renf);
    return 0;
  }

  if (tag < 4)
    ca = tag, ha = 1, sa = 0;
  else
    ca = *(*bp)++, sa = *(*bp)++, ha = *(*bp)++;  /* crypto, salt, hash type */

  if (sa & 1) {
    memcpy(hbuf, *bp, 8);       /* salt */
    memcpy(&hbuf[8], passph, strlen(passph));
    *bp += 8;
    k = 8 + strlen(passph);
    i = k;
  }
  switch (sa) {
  case 3:
    ic = *(*bp)++;              /* postfix - hash size */
    i = (16 + (ic & 15)) << ((ic >> 4) + 6);
    if (i < strlen(passph) + 8)
      i = strlen(passph) + 8;
    break;
  case 0:
    memcpy(hbuf, passph, strlen(passph));
    i = strlen(passph);
    k = i;
    break;
  case 1:
    break;
  default:
    return -1;
  }

  MemSet(passph,strlen(passph),0);
  MemHandleUnlock(thand);
  FrmDeleteForm(renf);

  PGP_khash(ha, i, k, PGP_cksz(ca), hbuf, hkobuf);

  if (tag == 0xff || tag < 4) {
    memcpy(hbuf, *bp, 8);
    *bp += 8;
  } else
    memset(hbuf, 0, 8);

  *ccfb = PGP_cini(hkobuf, hbuf, ca, 0);
  return tag;
}
