#include <stdio.h>
#include <string.h>
#include <rand.h>
#include "libpgp2.h"

/*------------------------------------*/
int pkeenc2(FILE * outf, unsigned long long keyid,
            unsigned char *passwdhash, int newckey)
{
  unsigned long ll, j;
  unsigned char dbuf[1024];
  RSA *key;

  if (newckey)
    RAND_bytes(passwdhash, 16);
  if (getkey2(&key, NULL, NULL, &keyid))  /* get pubkey */
    return 1;                   /* no pub key */
  dbuf[0] = 1;
  memcpy(&dbuf[1], passwdhash, 16);
  for (ll = 0, j = 1; j < 17; j++)  /* calculate checksum */
    ll += dbuf[j];
  dbuf[17] = ll >> 8;
  dbuf[18] = ll;                /*cksum */
  j = 8 * RSA_public_encrypt(19, dbuf, dbuf, key, RSA_PKCS1_PADDING);
  RSA_free(key);
  while (dbuf[0] == 0)
    memmove(dbuf, &dbuf[1], (j + 7) / 8), j -= 8;
  ll = dbuf[0];
  while (!(ll & 0x80)) {
    j--;
    ll <<= 1;
  }
  ll = 12 + (j + 7) / 8;
  fputc(0x85, outf);            /* header byte */
  fputc(ll >> 8, outf);         /* length */
  fputc(ll, outf);
  fputc(3, outf);               /* version byte - 3 */
  for (ll = 0; ll < 8; ll++)    /* key id */
    fputc(0xff & (keyid >> (56 - 8 * ll)), outf);
  fputc(1, outf);               /* algorithm ID */
  fputc(j >> 8, outf);
  fputc(j, outf);
  fwrite(dbuf, 1, (j + 7) / 8, outf);
  return 0;
}
