#ident "$Id: aes_file.c,v 1.3 2006/10/06 19:21:35 craig Exp $"
/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*
 * Encrypt or decrypt a file using AES.
 * The encryption key comes from a file.
 * The initial vector is all zeros.  This is designed to match what
 * the tmd program expects as input.
 */

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>

#include "aes.h"

#define AES_KEY_LENGTH          16
#define AES_IV_LENGTH           16

int aes_SwEncryptWrapper(uint8_t *key, uint8_t *initVector, uint8_t *dataIn,
                         uint32_t bytes,uint8_t *dataOut);
#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"decrypt",         0, 0, 'd'},     /* Print usage */
    {"help",            0, 0, 'h'},     /* Print usage */
    {"keyfile",         1, 0, 'k'},     /* AES key comes from this file */
    {"infile",          1, 0, 'i'},     /* Input data file */             
    {"outfile",         1, 0, 'o'},     /* Output file */             
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {0, 0, 0, 0}
};
#endif

static char* options = "dhk:i:v";

/* ------------------------------------------------------------------------ */
static void
usage(const char* const progName)
{
    printf (
        "Usage: %s (options) -k [key file name] -i [input name]\n"
        "       Options: -o [output name]\n"
        "       Options: -d                    (decrypt instead of encrypt)\n",
        progName);
}

/* ------------------------------------------------------------------------ */

static void
processOptions(int argc, char* argv[],
               char **key_file, char **input_file,
               char **output_file, bool *encrypt)
{
    *output_file = *input_file = *key_file = NULL;
    *encrypt = true;

    while (1) {
#if defined(__CYGWIN__)
        int ch = getopt(argc, argv, options);
#else
        int ch = getopt_long_only(argc, argv, options, longOptions, 0);
#endif

        if (ch == -1)
            break;

        switch (ch) {

        case 'd':
            *encrypt = false;
            break;

        case 'h':
            usage(argv[0]);
            exit(0);
            break;

        case 'i':
            *input_file = optarg;
            break;

        case 'k':
            *key_file = optarg;
            break;

        case 'o':
            *output_file = optarg;
            break;

        default:
            usage(argv[0]);
            exit(1);
        }
    }
    if (key_file == NULL) {
        fprintf(stderr, "(%s) Need key file name\n", argv[0]);
        usage(argv[0]);
        exit(1);
    }
    if (input_file == NULL) {
        fprintf(stderr, "(%s) Need input file name\n", argv[0]);
        usage(argv[0]);
        exit(1);
    }
} // processOptions

/* ------------------------------------------------------------------------ */

uint8_t aes_iv[] = {0x00, 0x00, 0x00, 0x00,
                    0x12, 0x34, 0xab, 0xcd,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00};
#define IO_SIZE         1024

int
main(int argc, char *argv[])
{
    uint8_t     aes_key[AES_KEY_LENGTH];
    uint32_t    in_buf[IO_SIZE], out_buf[IO_SIZE];
    char        *key_file_name, *in_file_name, *out_file_name;
    FILE        *key_file, *in_file, *out_file;
    size_t      bytes_read, bytes_written;
    bool        encrypt, done;

    processOptions(argc, argv, &key_file_name, &in_file_name, &out_file_name,
                   &encrypt);

    if ( (key_file = fopen(key_file_name, "r")) == NULL) {
        fprintf (stderr, "Can't open key file '%s' - exit\n", key_file_name);
        exit(1);
    }

    bytes_read = fread(aes_key, 1, AES_KEY_LENGTH, key_file);
    if (bytes_read != AES_KEY_LENGTH) {
        printf("(%s) Need %d key bytes from %s, only got %d - exit\n",
                argv[0], AES_KEY_LENGTH, key_file_name, bytes_read);
        exit(1);
    }
    fclose(key_file);
    memset(aes_iv, 0, AES_IV_LENGTH);

    if ( (in_file = fopen(in_file_name, "rb")) == NULL) {
        fprintf (stderr, "Can't open in file '%s' - exit\n", in_file_name);
        exit(1);
    }

    if (out_file_name != NULL) {
        if ( (out_file = fopen(out_file_name, "w")) == NULL) {
            fprintf (stderr, "Can't open out file '%s' - exit\n",
                     out_file_name);
            exit(1);
        }
    }
    else {
        out_file = stdout;
    }

    done = false;

    do {
        bytes_read = fread(in_buf, 1, sizeof(in_buf), in_file);
        if (bytes_read != sizeof(in_buf)) {
            done = true;
            if (ferror(in_file)) {
                fprintf(stderr, "Error reading input file - exiting\n");
                if (out_file != stdout) {
                    fclose(out_file);
                    unlink(out_file_name);
                    exit(1);
                }
            }
        }
        if (encrypt) {
            aes_SwEncryptWrapper((uint8_t *) &aes_key, (uint8_t *) &aes_iv,
                                 (uint8_t *) in_buf, bytes_read,
                                 (uint8_t *) out_buf);
        }
        else {
            aes_SwDecryptWrapper((uint8_t *) &aes_key, (uint8_t *) &aes_iv,
                                 (uint8_t *) in_buf, bytes_read,
                                 (uint8_t *) out_buf);
        }
        bytes_written = fwrite(out_buf, 1, bytes_read, out_file);
        if (bytes_written != bytes_read) {
            fprintf(stderr, "Error writing output file - exiting\n");
            fclose(out_file);
            unlink(out_file_name);
            exit(1);
        }
    } while (! done);
} // main
