//------------------------------------------------------------------------------
// File:          aes_reference.h
// Function:      Firmware encryption using AES reference implementation
// Supported chip(s):
//    - AT91SAM7XC128
//    - AT91SAM7XC256
// Supported toolchain(s):
//    - IAR Embedded Workbench
// Date created:  06 June 2006
// Created by:    JJo
//------------------------------------------------------------------------------

#ifndef BOOTLOADER_AES_REFERENCE_H
#define BOOTLOADER_AES_REFERENCE_H

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

#include "common.h"
#include "debug.h"
#include "timing.h"

#if defined(USE_ENCRYPTION) && defined(ENCRYPTION_AES_REF)

//------------------------------------------------------------------------------
// Check configuration
//------------------------------------------------------------------------------

// Supported modes
#if !defined(ENCRYPTION_ECB) && \
    !defined(ENCRYPTION_CBC) && \
    !defined(ENCRYPTION_CTR)
  #error No other mode than ECB, CBC & CTR are supported.
#endif

// Supported key length
#if (ENCRYPTION_KEY_LENGTH != 16) && \
    (ENCRYPTION_KEY_LENGTH != 24) && \
    (ENCRYPTION_KEY_LENGTH != 32) 
  #error Only key lengths of 128, 192 or 256 bits are supported.
#endif

// Supported block length
#if (ENCRYPTION_BLOCK_LENGTH != 16)
  #error Only block length of 128 bits is supported.
#endif

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

// Functions
#define encryption_init     aes_ref_init
#define encryption_cleanup  aes_ref_cleanup
#define encryption_decrypt  aes_ref_decrypt

#define BC                  (ENCRYPTION_BLOCK_LENGTH / 4)
#define SC	            ((BC - 4) >> 1)
#define KC                  (ENCRYPTION_KEY_LENGTH / 4)
#define t0f                 0x000000FF & tf
#define t1f                 0x0000FF00 & tf
#define t2f                 0x00FF0000 & tf
#define t3f                 0xFF000000 & tf

#if (KC >= BC)
  #define ROUNDS            (KC + 6)
#else
  #define ROUNDS            (BC + 6)
#endif

//------------------------------------------------------------------------------
// Prototypes
//------------------------------------------------------------------------------

void aes_ref_init(void);
void aes_ref_cleanup(void);
int aes_ref_decrypt(const unsigned char *, unsigned char *, unsigned int);

#endif // defined(USE_ENCRYPTION) && defined(ENCRYPTION_AES_REF)
#endif // BOOTLOADER_AES_REFERENCE_H
