﻿/*--------------------------------------------------------------------------------*
  Copyright (C)Nintendo All rights reserved.

  These coded instructions, statements, and computer programs contain proprietary
  information of Nintendo and/or its licensed developers and are protected by
  national and international copyright laws. 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 Nintendo.

  The content herein is highly confidential and should be handled accordingly.
 *--------------------------------------------------------------------------------*/
/*
 *  Copyright 2005-2014 Acer Cloud Technology, Inc.
 *  All Rights Reserved.
 *
 *  This software contains confidential information and
 *  trade secrets of Acer Cloud Technology, Inc.
 *  Use, disclosure or reproduction is prohibited without
 *  the prior express written permission of Acer Cloud
 *  Technology, Inc.
 */

/*
 *               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.
 *
 */
/*
 * implementations for integer math routines needed for the
 * ECDSA and RSA  algorithm. implemented using the array of  words big
 * integer notation
 *
 */

#include "crypto0_BigNumMath.h"
//#include <nn/nn_SdkAssert.h>

/* maximum length in digits */
#define MAX_BIGINT_DIGITS (4096 / BIGINT_DIGIT_BITS + 1)

/* supports up to 256 bit ECC*/
#define MAX_ECC_DIGITS (256 / BIGINT_DIGIT_BITS)

#define BIGINT_ASSIGN_DIGIT(a, b, digits) {bigint_zero(a, digits); a[0] = b; }

namespace nn { namespace crypto0 { namespace detail {

void bigint_digit_mult(bigint_digit a[2], bigint_digit b, bigint_digit c) NN_NOEXCEPT
{
    unsigned long long llres;

    llres = ((unsigned long long ) b) * ((unsigned long long) c);
    a[0] = (unsigned int) (llres & 0xffffffff);
    a[1] = (unsigned int) (llres >> 32);

}

/*
 * computes a = b - c*d for
 * a[] b[] d[] and c is a digit
 * return borrow
 */
static
bigint_digit bigint_sub_digit_mult(bigint_digit* a, const bigint_digit* b,
                                   const bigint_digit c, const bigint_digit* d,
                                   int digits) NN_NOEXCEPT
{
    bigint_digit borrow, t[2];
    int i;

    if (c == 0)
    {
        return (0);
    }

    borrow = 0;
    for (i = 0; i < digits; i++)
    {
        bigint_digit_mult(t, c, d[i]);
        if ((a[i] = b[i] - borrow) > (BIGINT_DIGIT_MAX - borrow))
        {
            borrow = 1;
        }
        else
        {
            borrow = 0;
        }
        if ((a[i] -= t[0]) > (BIGINT_DIGIT_MAX - t[0]))
        {
            borrow++;
        }
        borrow += t[1];
    }
    return borrow;
}

/*
 * returns how many bits are significant
 */
static
int bigint_digit_bits(bigint_digit a) NN_NOEXCEPT
{
    int i;
    for (i = 0; i < BIGINT_DIGIT_BITS; i++, a >>= 1)
    {
        if (a == 0)
        {
            break;
        }
    }
    return i;
}

/*
 * a = b/ c where all are digits
 * length of b is b[2]
 * b[1] < c and HIGHER_HALF(c) > 0
 */
typedef unsigned short bigint_half_digit;

enum
{
    BIGINT_HALF_DIGIT_BITS = (BIGINT_DIGIT_BITS / 2),
    LOW_MASK = 0x0000ffff
};

#define LOWER_HALF(x) ((x) & LOW_MASK)
#define HIGHER_HALF(x) (((x) >> BIGINT_HALF_DIGIT_BITS) & LOW_MASK)
#define TO_HIGHER_HALF(x) (((bigint_digit)(x)) << BIGINT_HALF_DIGIT_BITS)

static
void bigint_digit_div(bigint_digit* a, const bigint_digit b[2], bigint_digit c) NN_NOEXCEPT
{
    bigint_digit t[2], u, v;
    bigint_half_digit a_high, a_low, c_high, c_low;

    c_high = (bigint_half_digit) HIGHER_HALF(c);
    c_low = (bigint_half_digit) LOWER_HALF(c);

    t[0] = b[0];
    t[1] = b[1];

    /* under-estimate higher half of quotient and subtract */
    if (c_high == LOW_MASK)
    {
        a_high = (bigint_half_digit) HIGHER_HALF (t[1]);
    }
    else
    {
        a_high = (bigint_half_digit) (t[1] / (c_high + 1));
    }

    u = (bigint_digit) a_high * (bigint_digit) c_low;
    v = (bigint_digit) a_high * (bigint_digit) c_high;

    if ((t[0] -= TO_HIGHER_HALF(u)) > (BIGINT_DIGIT_MAX - TO_HIGHER_HALF(u)))
    {
        t[1]--;
    }
    t[1] -= HIGHER_HALF(u);
    t[1] -= v;

    /* correct estimate */
    while ((t[1] > c_high) ||
           ((t[1] == c_high) && (t[0] >= TO_HIGHER_HALF(c_low))))
    {
        if ((t[0] -= TO_HIGHER_HALF(c_low)) > BIGINT_DIGIT_MAX - TO_HIGHER_HALF(c_low))
        {
            t[1]--;
        }
        t[1] -= c_high;
        a_high++;
    }

    /* underestimate lower half of quotient and subtract */
    if (c_high == LOW_MASK)
    {
        a_low = (bigint_half_digit) LOWER_HALF(t[1]);
    }
    else
    {
        a_low = (bigint_half_digit) ((TO_HIGHER_HALF(t[1]) + HIGHER_HALF(t[0])) / (c_high + 1));
    }
    u = (bigint_digit) a_low * (bigint_digit) c_low;
    v = (bigint_digit) a_low * (bigint_digit) c_high;
    if ((t[0] -= u) > (BIGINT_DIGIT_MAX - u))
    {
        t[1]--;
    }
    if ((t[0] -= TO_HIGHER_HALF(v)) > (BIGINT_DIGIT_MAX - TO_HIGHER_HALF(v)))
    {
        t[1]--;
    }
    t[1] -= HIGHER_HALF(v);

    /* correct estimate */
    while ((t[1] > 0) || ((t[1] == 0) && t[0] >= c))
    {
        if ((t[0] -= c) > (BIGINT_DIGIT_MAX - c))
        {
            t[1]--;
        }
        a_low++;
    }
    *a = TO_HIGHER_HALF(a_high) + a_low;
}

/*
 * copies b to a
 */
void
bigint_copy(bigint_digit* a, const bigint_digit* b, int digits) NN_NOEXCEPT
{
    int i;
    for (i = 0; i < digits; i++)
    {
        a[i] = b[i];
    }
}

/*
 * zeros
 */
void bigint_zero(bigint_digit* a, int digits) NN_NOEXCEPT
{
    int i;
    for (i = 0; i < digits; i++)
    {
        a[i] = 0;
    }
}

/*
 * return length in digits
 */
int
bigint_digits(const bigint_digit* a, int digits) NN_NOEXCEPT
{
    int i;
    for (i = digits - 1; i >= 0; i--)
    {
        if (a[i])
        {
            break;
        }
    }

    return(i + 1);
}

/* Computes a = b * c.
   Lengths: a[2*digits], b[digits], c[digits].
*/
void
bigint_mult(bigint_digit* a, const bigint_digit* b, const bigint_digit* c, int digits) NN_NOEXCEPT
{
    int b_digits, c_digits, i;
    bigint_digit integer_math_res[2 * MAX_BIGINT_DIGITS];

    bigint_zero(integer_math_res, 2 * digits);

    b_digits = bigint_digits(b, digits);
    c_digits = bigint_digits(c, digits);

    for (i = 0; i < b_digits; i++)
    {
        integer_math_res[i + c_digits] += bigint_add_mult(&integer_math_res[i], c, c_digits, b[i]);
    }

    bigint_copy(a, integer_math_res, 2 * digits);
}

/*
 * a = b << c (shifts b left c bits)
 *return carry
 */
static
bigint_digit bigint_left_shift(bigint_digit* a, const bigint_digit* b, int c,
                               int digits) NN_NOEXCEPT
{
    bigint_digit bi, carry;
    int i, t;

    if (c >= BIGINT_DIGIT_BITS)
    {
        return (0);
    }

    t = BIGINT_DIGIT_BITS - c;
    carry = 0;
    for (i = 0; i < digits; i++)
    {
        bi = b[i];
        a[i] = (bi << c) | carry;
        carry = c ? (bi >> t) : 0;
    }
    return (carry);
}

/*
 * shifts b right c times and returns in a
 */
static
bigint_digit bigint_right_shift(bigint_digit* a, const bigint_digit* b, int c,
                                int digits) NN_NOEXCEPT
{
    bigint_digit bi, carry;
    int i;
    unsigned int t;

    if (c >= BIGINT_DIGIT_BITS)
    {
        return (0);
    }

    t = BIGINT_DIGIT_BITS - c;
    carry = 0;

    for (i = digits - 1; i >= 0; i--)
    {
        bi = b[i];
        a[i] = (bi >> c) | carry;
        carry = c ? (bi << t) : 0;
    }
    return (carry);
}

/*
 * compare and return sign of a-b
 */
int
bigint_cmp(const bigint_digit* a, const bigint_digit* b, int digits) NN_NOEXCEPT
{
    int i;

    for (i = digits - 1; i >= 0; i--)
    {
        if (a[i] > b[i])
        {
            return (1);
        }
        if (a[i] < b[i])
        {
            return (-1);
        }
    }
    return (0);
}

/*
 * a = c/d and b = c % d
 * a[c_digits], b[d_digits], c[c_digits], d[d_digits],
 * c_digits < 2*MAX_BIGINT_DIGITS
 */
void
bigint_div(bigint_digit* a, bigint_digit* b, const bigint_digit* c,
           int c_digits, const bigint_digit* d, int d_digits) NN_NOEXCEPT
{
    bigint_digit ai;
    bigint_digit t;
    int i, dd_digits, shift;
    bigint_digit integer_math_cc[2 * MAX_BIGINT_DIGITS + 1], integer_math_dd[MAX_BIGINT_DIGITS];

    dd_digits = bigint_digits(d, d_digits);
    if (dd_digits == 0)
    {
        return;
    }

    /* normalize */
    shift = BIGINT_DIGIT_BITS - bigint_digit_bits(d[dd_digits - 1]);
    bigint_zero(integer_math_cc, dd_digits);
    integer_math_cc[c_digits] = bigint_left_shift(integer_math_cc, c, shift, c_digits);
    bigint_left_shift(integer_math_dd, d, shift, dd_digits);
    t = integer_math_dd[dd_digits - 1];

    bigint_zero(a, c_digits);

    for (i = c_digits - dd_digits; i >= 0; i--)
    {
        /* underestimate quotient and subtract */
        if (t == BIGINT_DIGIT_MAX)
        {
            ai = integer_math_cc[i + dd_digits];
        }
        else
        {
            bigint_digit_div(&ai, &integer_math_cc[i + dd_digits - 1], t + 1);
        }
        integer_math_cc[i + dd_digits] -= bigint_sub_digit_mult(&integer_math_cc[i],
                                                                &integer_math_cc[i], ai,
                                                                integer_math_dd, dd_digits);
        /*correct estimate */
        while (integer_math_cc[i + dd_digits] ||
               (bigint_cmp(&integer_math_cc[i], integer_math_dd, dd_digits) >= 0))
        {
            ai++;
            integer_math_cc[i + dd_digits] -= bigint_sub(&integer_math_cc[i], &integer_math_cc[i],
                                                         integer_math_dd, dd_digits);
        }
        a[i] = ai;
    }
    bigint_zero(b, d_digits);
    bigint_right_shift(b, integer_math_cc, shift, dd_digits);
}

/*
 * compute a = b mod c
 * a[c_digits], b[b_digits], c[c_digits]
 * c > 0, b_digits < 2*MAX_BIGINT_DIGITS, c_digits < MAX_BIGINT_DIGITS
 */

void
bigint_mod(bigint_digit* a, const bigint_digit* b, int b_digits, const bigint_digit* c,
           int c_digits) NN_NOEXCEPT
{
    bigint_digit integer_math_mod_t[2 * MAX_BIGINT_DIGITS];
    bigint_div(integer_math_mod_t, a, b, b_digits, c, c_digits);
}

/*
 * a = b*c mod d
 */
void
bigint_mod_mult(bigint_digit* a, const bigint_digit* b, const bigint_digit* c,
                const bigint_digit* d, int digits) NN_NOEXCEPT
{
    bigint_digit integer_math_mod_mult_t[2 * MAX_BIGINT_DIGITS];
    bigint_mult(integer_math_mod_mult_t, b, c, digits);
    bigint_mod(a, integer_math_mod_mult_t, 2 * digits, d, digits);
}

/* a = b^c mod d.
 * Lengths: a[d_digits, b[d_digits], c[c_digits], d[d_digits].
 * Assumes d > 0, c_digits > 0, d_digits < MAX_BIGINT_DIGITS.
 */
#define BIGINT_DIGIT_2MSBS(x) (bigint_digit)(((x) >> (BIGINT_DIGIT_BITS - 2)) & 3)

void
bigint_mod_exp(bigint_digit* a, const bigint_digit* b, const bigint_digit* c,
               int c_digits, const bigint_digit* d, int d_digits) NN_NOEXCEPT
{

    bigint_digit ci;
    int i;
    unsigned int ci_bits, j, s;
    bigint_digit exp;
    unsigned int need[4];
    bigint_digit set_bits = 0;
    bigint_digit integer_math_b_power[3][MAX_BIGINT_DIGITS], integer_math_tt[MAX_BIGINT_DIGITS];
    /* zero and power one come for free */
    need[0] = 1;
    need[1] = 1;
    need[2] = 1;
    need[3] = 1;
    /* check input to see if power 3 is needed, then turn on 2. */
    exp = c[0];

    for (i = 0; i < 16; i++)
    {
        /* take last two bits */
        set_bits = exp & 0x00000003;
        /* you need to compute that power */
        need[set_bits]++;
        /* shift right two bits */
        exp = exp >> 2;
    }
    if (need[3] > 0)
    {
        need[2] = 1; /* need to compute anyway */
    }

    /* store b, b^2 mod d, and b^3 mod d */
    bigint_copy(integer_math_b_power[0], b, d_digits);
    if (need[2] > 0)
    {
        bigint_mod_mult(integer_math_b_power[1], integer_math_b_power[0], b, d, d_digits);
    }
    if (need[3] > 0)
    {
        bigint_mod_mult(integer_math_b_power[2], integer_math_b_power[1], b, d, d_digits);
    }
    BIGINT_ASSIGN_DIGIT(integer_math_tt, 1, d_digits);

    c_digits = bigint_digits(c, c_digits);

    for (i = c_digits - 1; i >= 0; i--)
    {
        ci = c[i];
        ci_bits = BIGINT_DIGIT_BITS;

        /* scan past leading zero bits of most significant digit */
        if (i == (int)(c_digits - 1))
        {
            while (!BIGINT_DIGIT_2MSBS(ci))
            {
                ci <<= 2;
                ci_bits -= 2;
            }
        }

        for (j = 0; j < ci_bits; j += 2, ci <<= 2)
        {
            /* compute t = t^4*b^s mod d, where s = two MSBs of ci */
            bigint_mod_mult(integer_math_tt, integer_math_tt, integer_math_tt, d, d_digits);
            bigint_mod_mult(integer_math_tt, integer_math_tt, integer_math_tt, d, d_digits);
            if ((s = BIGINT_DIGIT_2MSBS(ci)) != 0)
            {
                bigint_mod_mult(integer_math_tt, integer_math_tt, integer_math_b_power[s - 1], d,
                                d_digits);
            }
        }
    }
    bigint_copy(a, integer_math_tt, d_digits);

}

/*
 * return nonzero iff a is zero
 */
int
bigint_iszero(const bigint_digit* a, int digits) NN_NOEXCEPT
{
    int i;

    for (i = 0; i < digits; i++)
    {
        if (a[i])
        {
            return (0);
        }
    }

    return (1);
}

/* compute a = 1/b mod c
 * this is only for ecc, so use the smaller MAX_ECC_DIGITS
 * gcd(b,c)=1
 */
void
bigint_mod_inv(bigint_digit* a, const bigint_digit* b,
               const bigint_digit* c, int digits) NN_NOEXCEPT
{
    bigint_digit q[MAX_ECC_DIGITS], t1[MAX_ECC_DIGITS], t3[MAX_ECC_DIGITS],
                 u1[MAX_ECC_DIGITS], u3[MAX_ECC_DIGITS], v1[MAX_ECC_DIGITS],
                 v3[MAX_ECC_DIGITS], w[2 * MAX_ECC_DIGITS];
    int u1_sign;
    NN_SDK_ASSERT(digits <= MAX_ECC_DIGITS);

    /* apply extended euclidian alg modified to avoid neg numbers */
    BIGINT_ASSIGN_DIGIT(u1, 1, digits);
    bigint_zero(v1, digits);
    bigint_copy(u3, b, digits);
    bigint_copy(v3, c, digits);
    u1_sign = 1;

    while (!bigint_iszero(v3, digits))
    {
        bigint_div(q, t3, u3, digits, v3, digits);
        bigint_mult(w, q, v1, digits);
        bigint_add(t1, u1, w, digits);
        bigint_copy(u1, v1, digits);
        bigint_copy(v1, t1, digits);
        bigint_copy(u3, v3, digits);
        bigint_copy(v3, t3, digits);
        u1_sign = -u1_sign;
    }
    /* negate if sign is negative */
    if (u1_sign < 0)
    {
        bigint_sub(a, c, u1, digits);
    }
    else
    {
        bigint_copy(a, u1, digits);
    }
}

/* returns a = b + c mod d, when a <= d, b <= d.
   If it is not the case, returns a number a such that
   a mod d = b + c mod d and a < 2^digits */
void
bigint_add_mod(bigint_digit* a, const bigint_digit* b,
               const bigint_digit* c, const bigint_digit* d, int digits) NN_NOEXCEPT
{
    int carry, borrow;
    carry = bigint_add(a, b, c, digits);
    if (carry || (bigint_cmp(a, d, digits) > 0))
    {
        borrow = bigint_sub(a, a, d, digits);
        while (carry != borrow)
        {
            borrow = bigint_sub(a, a, d, digits);
        }
    }
}

/* returns a = b - c mod d, when a <= d, b <= d.
   If it is not the case, returns a number a such that
   a mod d = b - c mod d and a < 2^digits. */
void
bigint_sub_mod(bigint_digit* a, const bigint_digit* b,
               const bigint_digit* c, const bigint_digit* d, int digits) NN_NOEXCEPT
{
    int carry, borrow;
    borrow = bigint_sub(a, b, c, digits);
    if (borrow || (bigint_cmp(a, d, digits) > 0))
    {
        carry = bigint_add(a, a, d, digits);
        while (carry != borrow)
        {
            borrow = bigint_add(a, a, d, digits);
        }
    }
}

/* returns res = min(a, b) */
void bigint_min(bigint_digit* res, const bigint_digit* a, const bigint_digit* b, int digits) 
{
    if (bigint_cmp(a, b, digits) > 0)
        bigint_copy(res, b, digits); // a - b > 0 
    else
        bigint_copy(res, a, digits); // a - b < 0
}

void OctetStringFromDigits(void* a, size_t len, const bigint_digit* b, size_t nDigits) NN_NOEXCEPT
{
    size_t j = len;

    for (size_t i = 0; i < nDigits && j > 0; i++)
    {
        bigint_digit t = b[i];
        for (size_t u = 0; j > 0 && u < sizeof(bigint_digit) * 8; u += 8)
        {
            static_cast<uint8_t*>(a)[--j] = static_cast<uint8_t>(t >> u);
        }
    }

    while ( j > 0 )
    {
        static_cast<uint8_t*>(a)[--j] = 0;
    }
}

void DigitsFromOctetString(bigint_digit* a, size_t nDigits, const void* b, size_t len) NN_NOEXCEPT
{
    size_t j = len;
    size_t i = 0;
    for (; i < nDigits && j > 0; i++)
    {
        bigint_digit t = 0;
        for (size_t u = 0; j > 0 && u < sizeof(bigint_digit) * 8; u += 8)
        {
            t |= static_cast<const uint8_t*>(b)[--j] << u;
        }
        a[i] = t;
    }
    for (; i < nDigits; i++)
    {
        a[i] = 0;
    }
}

}}} // namespace nn::crypto0::detail
