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

/*
 * Highest Level Crypto Services Library API
 */


#include "algorithms.h"
#include "elliptic_math.h"
#include "algorithms.h"
#include "csl.h"
#include "aes.h"
#include "sha1.h"
#include "integer_math.h"
#include "conversions.h"
#if defined(SC)
#include <ioslibc.h>
#elif defined(RVL)
#include <ioslibc.h>
#else
#include <string.h>
#endif

extern void bcopy();
extern void bzero();

    
/* 
 * Call to verify RSA signature, 
 * returns CSL_OK or CSL_VERIFY_ERROR : only supports exponents 3, 17, 65537.
 */

CSL_error
CSL_VerifyRsaSig(CSLOSSha1Hash hash, CSLOSRsaPublicKey certpublickey, CSLOSRsaSig certsign, CSLOSRsaExponent certexponent, u32 expsize, u32 keysize){
 
    u32 eDigits, nDigits, n;
    u8 result[MAX_BIGINT_DIGITS * BIGINT_DIGIT_BYTES];
    u8 *p, match;
    bigint_digit bign[MAX_BIGINT_DIGITS];
    bigint_digit bigm[MAX_BIGINT_DIGITS];
    bigint_digit bige[MAX_BIGINT_DIGITS];
    bigint_digit  bigc[MAX_BIGINT_DIGITS];
    int outlen;
    static u8 sha1_sig[16] = { 0x00,
	0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
	0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14
    };
        
    nDigits = keysize/BIGINT_DIGIT_BYTES;
    eDigits = 1;

    OS2IP (bign, nDigits, certpublickey, keysize);
    OS2IP (bigm, nDigits, certsign, keysize);
    OS2IP (bige, eDigits, certexponent, expsize);
    bigint_mod_exp(bigc, bigm, bige, eDigits, bign, nDigits);
    
    outlen = ((keysize * 8) + 7)/8;
    I2OSP(result, outlen, bigc, nDigits); 
	
    p = result;
    match = (p[0] == 0x00) & (p[1] == 0x01);
    for(p += 2; p < result + keysize - sizeof(CSLOSSha1Hash) - sizeof(sha1_sig); ) {
	match &= (*p++ == 0xff);
    }
    for(n = 0; n < sizeof(sha1_sig); n++) {
	match &= (*p++ == sha1_sig[n]);
    }
#if defined(RVL_DEVEL)
    /* 
     * This ifdef is to support existing tools for developers that incorrectly
     * generate the padding for the RSA signature. Therefore, to remain 
     * backward compatible, we can only check the 20-byte hash and not the 
     * entire signature which should be padded using PKCS#1 v1.5 type 2 
     * padding (officially EMSA-PKCS1-v1_5).
     * For production images, we are using the correct padding (via HSM).
     * See bug #2855, #2876.
     */
    match = 1;
#endif
    for(n = 0; n < sizeof(CSLOSSha1Hash); n++) {
	match &= (*p++ == *hash++);
    }
    return(match? CSL_OK : CSL_VERIFY_ERROR);
}

CSL_error CSL_VerifyRsaSig2048(CSLOSSha1Hash hash, 
                           CSLOSRsaPublicKey2048 certpublickey, 
                           CSLOSRsaSig2048 certsign, 
                           CSLOSRsaExponent certexponent, 
                               u32 expsize){
    return CSL_VerifyRsaSig(hash, certpublickey, certsign, certexponent, 
                            expsize, 256);
}



CSL_error CSL_VerifyRsaSig4096(CSLOSSha1Hash hash, 
                           CSLOSRsaPublicKey4096 certpublickey, 
                           CSLOSRsaSig4096 certsign, 
                           CSLOSRsaExponent certexponent, 
                               u32 expsize){
    return CSL_VerifyRsaSig(hash, certpublickey, certsign, certexponent, 
                            expsize, 512);
}


/* 
 * Sign call for testing support. This is not optimized for device use
 * message should be hashed, padded as per PKCS-1 type 2
 * before this function is called 
 */

void 
CSL_ComputeRsaSig(CSLOSRsaSig result, CSLOSRsaMsg paddedmessage, CSLOSRsaPublicKey certpublickey, CSLOSRsaSecretExp secretexponent, u32 keysize){

    u32 dDigits, nDigits;
    bigint_digit bign[MAX_BIGINT_DIGITS];
    bigint_digit bigm[MAX_BIGINT_DIGITS];
    bigint_digit bigd[MAX_BIGINT_DIGITS]; /* secret exp */
    bigint_digit  bigc[MAX_BIGINT_DIGITS];
    int outlen;
    
    nDigits = keysize/BIGINT_DIGIT_BYTES;
    dDigits = keysize/BIGINT_DIGIT_BYTES;
            
    OS2IP (bign, nDigits, certpublickey, keysize);
    OS2IP (bigm, nDigits, paddedmessage, keysize);
    OS2IP (bigd, dDigits, secretexponent, keysize);
                
    bigint_mod_exp(bigc, bigm, bigd, dDigits, bign, nDigits);
    
    outlen = ((keysize * 8) + 7)/8;
        
    I2OSP(result, outlen, bigc, nDigits); 
}


#if 0
/* using Garners algorithm and Chinese Remainder theorem. 
 * see the derivation on page 613 in handbook of applied cryptography
 * use factors dp and dq of secret exponent d and p and q of public 
 * exponent n, and qinv
 */
void
CSL_ComputeRsaSigFast(u8 *result, u32 *message, u32 *certpublickey, u32 *certp, u32 *certq, u32 *dmp, u32 *dmq, u32 *qinv,  int num_bits){
    u32 pDigits, qDigits, dmpDigits, dmqDigits, cDigits, nDigits, qinvDigits;
    bigint_digit bigp[MAX_BIGINT_DIGITS];
    bigint_digit bigq[MAX_BIGINT_DIGITS];
    bigint_digit  bigc[MAX_BIGINT_DIGITS];
    bigint_digit bigdmp[MAX_BIGINT_DIGITS];
    bigint_digit bigdmq[MAX_BIGINT_DIGITS]; 
    bigint_digit bigqinv[MAX_BIGINT_DIGITS];
    bigint_digit bign[MAX_BIGINT_DIGITS];
    bigint_digit cP[MAX_BIGINT_DIGITS];
    bigint_digit cQ[MAX_BIGINT_DIGITS];
    bigint_digit mP[MAX_BIGINT_DIGITS];
    bigint_digit mQ[MAX_BIGINT_DIGITS];
    bigint_digit temp[MAX_BIGINT_DIGITS];

    int outlen;
    int i;
    int num_words = num_bits/BIGINT_DIGIT_BITS;
    
    bigint_zero(bigp, MAX_BIGINT_DIGITS);
    bigint_zero(bigq, MAX_BIGINT_DIGITS);
    bigint_zero(bigdmp, MAX_BIGINT_DIGITS);
    bigint_zero(bigdmq, MAX_BIGINT_DIGITS);
    bigint_zero(bigqinv, MAX_BIGINT_DIGITS);
    bigint_zero(bigc, MAX_BIGINT_DIGITS);
    

    for(i =0; i < num_words/2; i++){
        bigp[num_words/2 - 1 - i] = certp[i];
	bigq[num_words/2 - 1 - i] = certq[i];
	bigdmp[num_words/2 - 1 - i] = dmp[i];
	bigdmq[num_words/2 - 1 - i] = dmq[i];
	bigqinv[num_words/2 - 1 - i] = qinv[i];
    }
    for(i =0; i < num_words; i++){
	bigc[num_words - 1 - i] = message[i];
	bign[num_words - 1 - i] = certpublickey[i];
    }
    cDigits = bigint_digits(bigc, MAX_BIGINT_DIGITS);
    pDigits = bigint_digits(bigp, MAX_BIGINT_DIGITS);
    qDigits = bigint_digits(bigq, MAX_BIGINT_DIGITS);
    dmpDigits = bigint_digits(bigdmp, MAX_BIGINT_DIGITS);
    dmqDigits = bigint_digits(bigdmq, MAX_BIGINT_DIGITS);
    qinvDigits = bigint_digits(bigqinv, MAX_BIGINT_DIGITS);
    nDigits = bigint_digits(bign, MAX_BIGINT_DIGITS);
    
    /* compute cP and cQ 
     */
    
    bigint_mod(cP, bigc, cDigits, bigp, pDigits);
    bigint_mod(cQ, bigc, cDigits, bigq, qDigits);

    /*
     * Compute mP = cP^dP mod p  and  mQ = cQ^dQ mod q. 
     */
    bigint_mod_exp(mP, cP, bigdmp, pDigits, bigp, pDigits);
    bigint_zero(mQ, nDigits);
    bigint_mod_exp(mQ, cQ, bigdmq, pDigits, bigq, pDigits);

    /* do CRT 
     * m = ((((mP - mQ) mod p)*qinv) mod p) *q + mQ
     */
    if(bigint_cmp(mP, mQ, pDigits) >=0)
      bigint_sub(temp, mP, mQ, pDigits);

    else{
      bigint_sub(temp, mQ, mP, pDigits);
      bigint_sub(temp, bigp, temp, pDigits);
    }
    
    bigint_mod_mult(temp, temp, bigqinv, bigp, pDigits);
    bigint_mult(temp, temp, bigq, pDigits);
    bigint_add(temp, temp, mQ, nDigits);
      
    outlen = (num_bits + 7)/8;
    I2OSP(result, outlen, temp, nDigits); 
}


/* HMAC needs key material of length 20 bytes to support HMAC-SHA1-80
 * and the result is truncated outside
 */

void
CSL_ComputeHmac(u8 *text, u32 text_length, 
		u8 *key, u32 key_length, u8 *hmac){
	SHA1Context sha;
	u8 k_ipad[65]; /* inner padding */
	u8 k_opad[65]; /* outer padding */

	u8 tk[16];
	
	int i;
	
	/* if key is longer than 64 bytes set it to key = SHA1(key)
	*/
	if(key_length > 64){
		SHA1Reset(&sha);
    		SHA1Input(&sha, key, key_length);
    		SHA1Result(&sha, tk);
		key = tk;
		key_length = 20;
	}
	/* the HMAC = SHA1(K xor opad, SHA1(K xor ipad, text))
	*/
	bzero(k_ipad, sizeof(k_ipad));
	bzero(k_opad, sizeof(k_opad));
	bcopy(key, k_ipad, key_length);
	bcopy(key, k_opad, key_length);

	/* xor key with ipad and opad values */
	for(i=0; i < 64; i++){
		k_ipad[i] ^= 0x36;
		k_opad[i] ^= 0x5c;
	}
	
	/* perform inner SHA1 */
	SHA1Reset(&sha);
	SHA1Input(&sha, k_ipad, 64);
	SHA1Input(&sha, text, text_length);
	SHA1Result(&sha, hmac);
	
	/* perform outer SHA1 */
	SHA1Reset(&sha);
	SHA1Input(&sha, k_opad, 64);
	SHA1Input(&sha, hmac, 16);
	SHA1Result(&sha, hmac);

	/* truncate outside */

}

#endif
