#ident "$Id: decrypt_common.c,v 1.5 2008/01/09 19:51:20 jprincen Exp $"
/*
 *               Copyright (C) 2006, 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.
 *
 */


#ifdef __CYGWIN__
#undef __STRICT_ANSI__
#else
#define fseeko(file, where, whence)     fseeko64(file, where, whence)
#define ftello(file)                    ftello64(file)
#endif

/*
 * Need to define this, or else on Cygwin the ticket and tmd
 * structures are laid out differently than on Linux
 */
#define BROADWAY_REV
#include <ctype.h>
#include <getopt.h>
#include <netinet/in.h>         // For htonl()
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/wait.h>           // for WEXITSTATUS()
#include <unistd.h>

#include "aes.h"
#include "sha1.h"
#include "image_superblock.h"
#include "types.h"
#include "disk_format.h"

extern char     *ProgName;
extern bool     Verbose;
void            dumpBytes (const u8* const ptr, const int length);

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

/*
 * ACTION:
 *           Compute the hash value of length 'hashArrayLength'
 *           bytes pointed to by 'hashArray'.  Compare that hash value
 *           against the value pointed at by 'hashValuePtr'.
 * RETURNS:
 *           true   -  if the hashes verify
 *           false  -  if they don't or some other error occurs.
 */
bool
verifyHashArray(u8* dataArray, const u32 dataArrayLength,
                const u8* const hashValuePtr)
{
    SHA1Context    context;
    u8             hashResult[SHA1_DIGESTSIZE];


    SHA1Reset(&context);
    SHA1Input(&context, dataArray, dataArrayLength);
    SHA1Result(&context, hashResult);

    if (memcmp(hashResult, hashValuePtr, SHA1_DIGESTSIZE) != 0) {
        if (Verbose) {
            fprintf(stdout, "%s: Hash miscompare - value is: ", ProgName);
            dumpBytes(hashResult,  SHA1_DIGESTSIZE);
            fprintf(stdout, "Should be: ");
            dumpBytes(hashValuePtr, SHA1_DIGESTSIZE);
        }
        return(false);
    }
    else {
        return(true);
    }
}

void
computeHash(u8* dataArray, const u32 dataArrayLength,
            u8* hashValuePtr)
{
    SHA1Context    context;
    u8             hashResult[SHA1_DIGESTSIZE];

    SHA1Reset(&context);
    SHA1Input(&context, dataArray, dataArrayLength);
    SHA1Result(&context, hashResult);

    memcpy(hashValuePtr, hashResult, SHA1_DIGESTSIZE);

}

/* ------------------------------------------------------------------------ */
static bool textToBytes(const char *textPtr, u8 *binPtr, const int numBytes);

bool
getAesKeyFromTextFile(const char* const fileName, u8 **decryptKey)
{
    FILE        *keyFile = NULL;
    char        line[AES_KEY_LENGTH * 2 + 80];  // 80 is fudge number
    char        *bufPtr, *startPtr;
    bool        returnVal = true;
    
    *decryptKey = (u8 *) malloc(AES_KEY_LENGTH);
    if (*decryptKey == NULL) {
        fprintf (stderr, "(%s) Can't malloc %d bytes\n",
                 ProgName, AES_KEY_LENGTH);
        returnVal = false;
        goto end;
    }


    if ( (keyFile = fopen(fileName, "r")) == NULL) {
        fprintf (stderr, "(%s) Can't open file %s for reading\n",
                 ProgName, fileName);
        returnVal = false;
        goto end;
    }
    if (fgets(line, sizeof(line), keyFile) == NULL) {
        fprintf (stderr, "(%s) Can't read a line from file %s\n",
                 ProgName, fileName);
        returnVal = false;
        goto end;
    }
    bufPtr = line;

    /* Skip any initial space */
    while (isspace(*bufPtr) && *bufPtr != '\0') {
        bufPtr++;
    }
    startPtr = bufPtr;

    while (isxdigit(*bufPtr) && *bufPtr != '\0') {
        bufPtr++;
    }
    *bufPtr = '\0';

    if (strlen(startPtr) != (AES_KEY_LENGTH * 2)) {
        fprintf (stderr, "(%s) Key length is incorrect - length is %d,"
                          " should be %d\n",
                          ProgName, strlen(startPtr), AES_KEY_LENGTH * 2);
        returnVal = false;
        goto end;
    }

    *decryptKey = (u8 *) malloc(AES_KEY_LENGTH);
    if (*decryptKey == NULL) {
        fprintf (stderr, "(%s) Can't malloc %d bytes\n",
                 ProgName, AES_KEY_LENGTH);
        returnVal = false;
        goto end;
    }
    if (textToBytes(startPtr, *decryptKey, AES_KEY_LENGTH) == false) {
        returnVal = false;
        goto end;
    }

end:
    if (keyFile != NULL) {
        fclose(keyFile);
        keyFile = NULL;
    }
    return(returnVal);
}

/* ------------------------------------------------------------------------ */
static bool
charToNibble(const char ch, u8 *value)
{
    if (isxdigit(ch)) {
        if (isdigit(ch)) {
            *value = (int) ch - (int) '0';
        }
        else if (isupper(ch)) {
            *value = ((int) ch - 'A') + 10;
        }
        else {
            *value = ((int) ch - 'a') + 10;
        }
        return(true);
    }
    else {
        return(false);
    }
}
/* ------------------------------------------------------------------------ */
/*
 * Convert the bytes represented as text in the string starting
 * at startPtr into binary.
 */
static bool
textToBytes(const char *textPtr, u8 *binPtr, const int numBytes)
{
    const char          *curInPtr;
    char                *curOutPtr;

    curInPtr  = textPtr;
    curOutPtr = binPtr;

    if (strlen(textPtr) * 2 < numBytes) {
        fprintf(stderr, "(%s): Text string too small in %s\n",
                ProgName, __FUNCTION__);
        return(false);
    }
    for (int i = 0; i < numBytes; i++) {
        u8      highNibble, lowNibble;

        if (charToNibble(textPtr[2 * i], &highNibble) == false) {
            fprintf(stderr, "(%s) Bad character (%c) in hex string\n",
                            ProgName, textPtr[2 * i]);
            return(false);
        }
        if (charToNibble(textPtr[2 * i + 1], &lowNibble) == false) {
            fprintf(stderr, "(%s) Bad character (%c) in hex string\n",
                            ProgName, textPtr[2 * i + 1]);
            return(false);
        }
        *curOutPtr++ = (highNibble << 4) | lowNibble;
    }
    return(true);
} // textToBytes
/* ------------------------------------------------------------------------ */
void
dumpBytes (const u8* const ptr, const int length)
{
    for (int i = 0; i < length; i++) {
        if (i % 16 == 0)
            printf ("\n0x%03x: ", i);
        printf ("%02x ", ptr[i]);
    }
    printf ("\n");
}
/* ------------------------------------------------------------------------ */


