/*
 *               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.
 *
 */

/* 
 * Utilities used in bsl.c
 */

#include <types.h>
#include <iosctypes.h>
#include <csl.h>
#include <bsl.h>
#include <ioslibc.h>
#include <sha1.h>
#include <aes.h>
#include "bslutils.h"
#include "keystore.h"

IOSCError
getSizeFromType(u8 keytype, u8 keysubtype, u32 *keySize)
{
    
    IOSCError error = IOSC_ERROR_OK;
        
    switch (keytype) {
    case IOSC_SECRETKEY_TYPE:
        switch (keysubtype) {
        case IOSC_ENC_SUBTYPE: 
            *keySize = sizeof(CSLOSAesKey);
            break;
        case IOSC_MAC_SUBTYPE:
            *keySize = sizeof(CSLOSHMACKey);
            break;
        case IOSC_ECC233_SUBTYPE:
            *keySize = sizeof(CSLOSEccPrivateKey);
            break;
        default:
            return IOSC_ERROR_INVALID;
        }
        break;
    case IOSC_PUBLICKEY_TYPE:
        switch (keysubtype) {
        case IOSC_ECC233_SUBTYPE:
            *keySize = sizeof(CSLOSEccPublicKey);
            break;
        case IOSC_RSA2048_SUBTYPE:
            *keySize = sizeof(CSLOSRsaPublicKey2048);
            break;
        case IOSC_RSA4096_SUBTYPE:
            *keySize = sizeof(CSLOSRsaPublicKey4096);
            break;
        default:
            return IOSC_ERROR_INVALID;
        }
        break;
    case IOSC_KEYPAIR_TYPE:
        switch (keysubtype) {
        case IOSC_ECC233_SUBTYPE:
            *keySize = sizeof(CSLOSEccPrivateKey) + sizeof(CSLOSEccPublicKey);
            break;
        default:
            return IOSC_ERROR_INVALID;
        }
        break;
    case IOSC_DATA_TYPE:
        switch (keysubtype) {
        case IOSC_VERSION_SUBTYPE:
            *keySize = 0;
            break;
        case IOSC_CONSTANT_SUBTYPE:
            *keySize = 0;
            break;
        default: 
            return IOSC_ERROR_INVALID;
        }        
        break;
    default:
        return IOSC_ERROR_INVALID;
    }    
    return error;
}

u32 
getExpSize(CSLOSRsaExponent exponent, u32 maxSize){
    int trailingZeros = 0;
    int i;
    /* find trailing zeros */
    for(i = maxSize -1; i >= 0; i--){
        if(exponent[i] != 0x0){
            break;
        }
        trailingZeros++;
    }
    return maxSize - trailingZeros;
}
 

void
getKeyTypeSubtype(IOSCKeyHandle handle, u8 *keytype, u8 *keysubtype)
{
    u8 type;
    /* special case root key handle */
    if (handle == IOSC_ROOT_KEY_HANDLE) {
        *keytype = IOSC_PUBLICKEY_TYPE;
        *keysubtype = IOSC_RSA4096_SUBTYPE;
    } else {
        keyGetType(handle, &type);
        *keytype = ((type & BSL_TYPE_MASK)>>BSL_TYPE_SHIFT);
        *keysubtype = (type & BSL_SUBTYPE_MASK);
    }
    return;
}


#if !defined(LINUX) && !defined(_WIN32)
extern IOSCError __iosDecrypt (IOSCSecretKeyHandle decryptHandle, u8 * ivData, u8 * inputData, u32 inputSize, u8 * outputData, s32, void *);

#endif


#ifndef HWCRYPTO
int
computeHMAC(u8 * context,
	    void * inputData, 
            u32 inputSize, 
            void *customData, 
            u32 customDataSize, 
            CSLOSHMACKey hmackey,  
	    u32 chainingFlag,
            void * signData)
{
    
    int i;
    u8 hashData[CSL_SHA1_DIGESTSIZE]; /* overallocate to align */
    /* align to 16 byte boundary */
    u8 ipad[CSL_SHA1_BLOCKSIZE], opad[CSL_SHA1_BLOCKSIZE];
    u8 kext[CSL_SHA1_BLOCKSIZE];
    u8 kxorpad[CSL_SHA1_BLOCKSIZE];

    IOSCError error = IOSC_ERROR_OK;
    
    memset(ipad, 0x36, CSL_SHA1_BLOCKSIZE);
    memset(opad, 0x5C, CSL_SHA1_BLOCKSIZE);
    
    /* extend it with zeros and write to kext */
    memcpy(kext, hmackey, sizeof(CSLOSHMACKey));
    memset(kext + sizeof(CSLOSHMACKey), 0x0, sizeof(kext) - sizeof(CSLOSHMACKey));
    
       
    for (i = 0; i < CSL_SHA1_BLOCKSIZE; i++) {
        kxorpad[i] = kext[i] ^ ipad[i];
    }
    if(chainingFlag == IOSC_MAC_FIRST){
      SHA1Reset((SHA1Context *)context);
      
      /* H(K xor opad, H(K xor ipad, text)) */
      SHA1Input((SHA1Context *)context, (SHA1_BYTE *) kxorpad, CSL_SHA1_BLOCKSIZE);
    }
    
    
    /* prepend custom data */
    if (customDataSize != 0) {
        SHA1Input((SHA1Context *)context, (SHA1_BYTE *) customData, customDataSize);
    }
    if  (inputSize != 0){
      SHA1Input((SHA1Context *)context,(SHA1_BYTE *)inputData, inputSize);
    }
    
    if(chainingFlag == IOSC_MAC_LAST){
      SHA1Result((SHA1Context *)context,(SHA1_BYTE *)(hashData));
      
   
      /* second hash */
      for (i = 0; i < CSL_SHA1_BLOCKSIZE; i++) {
        kxorpad[i] = kext[i] ^ opad[i];
      }
      SHA1Reset((SHA1Context *)context);
      SHA1Input((SHA1Context *)context,(SHA1_BYTE *)(kxorpad), CSL_SHA1_BLOCKSIZE);
      SHA1Input((SHA1Context *)context,(SHA1_BYTE *)hashData, CSL_SHA1_DIGESTSIZE);
      SHA1Result((SHA1Context *)context,(SHA1_BYTE *)signData);
    }
    return error;
}
#endif

unsigned long int 
wordswap(unsigned long int input)
{
    unsigned long output;
#ifdef LITTLE_ENDIAN
    output = ((input & 0xff) << 24 | ((input & 0xff00) << 8) | ((input & 0xff0000) >> 8) | ((input & 0xff000000) >> 24));
#else
    output = input;
#endif
    return output;
}

int
generateUnsignedCert(const char* certName, const char* issuerName, IOSCCertSigType sigType, IOSCCertPubKeyType keyType, u8* pubKey, u8* exponent, int exponentSizeInBytes, u32 date, u8* cert)
{
    IOSCEccEccCert* pcert;

    switch (sigType) {
    case IOSC_SIG_ECC:
        switch (keyType) {
        case IOSC_PUBKEY_ECC: 
            pcert = (IOSCEccEccCert*)cert;
            pcert->sig.sigType = wordswap(sigType);
            memset(pcert->sig.dummy, 0x0, sizeof(IOSCSigDummy));
            memset(pcert->sig.eccPad, 0x0, sizeof(IOSCEccPublicPad));
            memcpy(pcert->sig.issuer, issuerName, sizeof(IOSCName));
            pcert->head.pubKeyType = wordswap(keyType);
            memcpy(pcert->head.name.deviceId, certName, sizeof(IOSCName));
            pcert->head.date = wordswap(date);
            memcpy(pcert->pubKey, pubKey, sizeof(CSLOSEccPublicKey));
            memset(pcert->eccPad, 0x0, sizeof(IOSCEccPublicPad));
            memset(pcert->pad, 0x0, sizeof(IOSCCertPad));
            memset(pcert->pad2, 0x0, sizeof(IOSCEccCertPad));
            break;
        default:
            return IOSC_ERROR_INVALID_FORMAT;
        }
        break;
    default:
        return IOSC_ERROR_INVALID_FORMAT;
    }

    return IOSC_ERROR_OK;
}
