/*  MAC-f2
 *    This file contains an implementation of whatever it is that
 *    MAC-f1 is deemed to do. In this case, MAC-f1 simply takes an
 *    arbitrary length string and calculates DES(string), returning
 *    that as output. for security reasons, the program can't be
 *    called with the key as argument, so instead, it is passed the
 *    key in as the first string, and all the following strings are
 *    encrypted under that key.
 *
 *  Written by Yoav Yerushalmi as part of the MAC.el package, see
 *  comments in MAC.el for further info.
 */

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>

#define MAX_BLOCK_LEN 1024
        /* maximum size of input in any one string */

#define   parse(a)        ((16 * (a)[0]) + (a)[1])

void outfun(unsigned char);

int main() {
  char input[9], output[9];
  char str[MAX_BLOCK_LEN+1];
  unsigned char temp[MAX_BLOCK_LEN + 1];
  unsigned char out[MAX_BLOCK_LEN+1];
  int ref;
  int len, outputlen;

  signal(SIGHUP, exit);  /* terminate when we get sighup */
  memset(str, '\0', MAX_BLOCK_LEN);
  if (!fgets(str, MAX_BLOCK_LEN, stdin)) {
    perror("MAC-f2 failed to get key : ");
    exit(1);
  }
  des_setkey(str);
  while (fgets(str, MAX_BLOCK_LEN, stdin)) {
    len = strlen(str) - 1;
    len = (len / 3);
    ref = 0;
    while (ref < len) {
      temp[ref] = (unsigned char)strtol(&str[(ref * 3)], NULL, 16);
      ref++;
    }
    memcpy(str, temp, ref);
    str[len] = '\0'; /* remove the trailing newline */
    outputlen = 0;
    len -= 8;
    ref = 0;
    while (ref <= len) {
      outputlen+=8;
      memcpy(input, &str[ref], 8);
      des_cipher(input, output, 0, 1);
      memcpy(&out[ref], output, 8);
      ref += 8;
    }
    if (ref < (len+8)) {
      outputlen += 8;
      memset(input, '\0', 8);
      strcpy(input, &str[ref]);
      des_cipher(input, output, 0, 1);
      memcpy(&out[ref], output, 8);
    }
    for (ref=0; ref < outputlen; ref++)
      outfun(out[ref]);
    printf("\n");
    fflush(stdout);
  }
}


void outfun(unsigned char foo)
{
  printf("%02x ", foo);
}
