/*
* catwo.c
*
* A simple-minded encryptor and decryptor application.
*
* Usage:  catwo {[-e] | -d} key-string  < infile  > outfile
*
* The switch "-d" calls for decryption, whereas the optional
* switch "-e" entails encryption.
*
* The argument "key-string" is required to contain at least
* two characters, and will be truncated at 32 characters.
* The program reads from STDIN and writes to STDOUT.
*
* Of technical reasons, the encrypted output will be increased
* to a size of the nearest multiple of 16. Likewise, any decrypted
* output will be padded with NUL until a similar size condition holds.
*
* Author: Mats Erik Andersson
* Licensed under the same conditions as Niels Ferguson's libtwofish,
* alias TwofishClibc.
*/

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

#include <twofish.h>

#define MIN_KEYLEN 2

int main(int argc, char * argv[]) {
	size_t keylen;
	int shift = 1, encrypt = 1;
	Twofish_Byte key[32];
	Twofish_key xkey;
	Twofish_Byte inblock[16], outblock[16];

	memset(key, 0, sizeof(key));

	if (argc < 2)
		return 1; /* No key is possible.  */

	if (strcmp(argv[1], "-d") == 0)
		encrypt = 0;
	else if (strcmp(argv[1], "-e") != 0)
		shift = 0;

	if (argc - shift < 2)
		return 1; /* No key is possible.  */

	keylen = strlen(argv[1 + shift]);

	if (keylen < MIN_KEYLEN) {
		fprintf(stderr, "Key material too short.\n");
		return 1;
	}

	if (keylen > sizeof(key))
		keylen = sizeof(key);

	Twofish_initialise();

	strncpy((char *) key, argv[1 + shift], sizeof(key));

	memset(inblock, 0, sizeof(inblock));

	Twofish_prepare_key(key, keylen, &xkey);

	while (read(STDIN_FILENO, inblock, sizeof(inblock)) > 0) {
		if (encrypt)
			Twofish_encrypt(&xkey, inblock, outblock);
		else
			Twofish_decrypt(&xkey, inblock, outblock);

		write(STDOUT_FILENO, outblock, sizeof(outblock));

		memset(inblock, 0, sizeof(inblock));
	}

	return 0;
}
