/* ***************************************************************** *
 * Copyright 1998 International Business Machines Corporation. All   *
 * Rights Reserved.                                                  *
 *                                                                   *
 * Please read this carefully.  Your use of this reference           *
 * implementation of certain of the IETF public-key infrastructure   *
 * specifications ("Software") indicates your acceptance of the      *
 * following.  If you do not agree to the following, do not install  *
 * or use any of the Software.                                       *
 *                                                                   *
 * Permission to use, reproduce, distribute and create derivative    *
 * works from the Software ("Software Derivative Works"), and to     *
 * distribute such Software Derivative Works is hereby granted to    *
 * you by International Business Machines Corporation ("IBM").  This *
 * permission includes a license under the patents of IBM that are   *
 * necessarily infringed by your use of the Software as provided by  *
 * IBM.                                                              *
 *                                                                   *
 * IBM licenses the Software to you on an "AS IS" basis, without     *
 * warranty of any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL         *
 * WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING,   *
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF       *
 * MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR    *
 * PURPOSE.  You are solely responsible for determining the          *
 * appropriateness of using this Software and assume all risks       *
 * associated with the use of this Software, including but not       *
 * limited to the risks of program errors, damage to or loss of      *
 * data, programs or equipment, and unavailability or interruption   *
 * of operations.                                                    *
 *                                                                   *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, *
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC              *
 * CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN   *
 * IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  IBM  *
 * will not be liable for the loss of, or damage to, your records or *
 * data, or any damages claimed by you based on a third party claim. *
 *                                                                   *
 * IBM wishes to obtain your feedback to assist in improving the     *
 * Software.  You grant IBM a world-wide, royalty-free right to use, *
 * copy, distribute, sublicense and prepare derivative works based   *
 * upon any feedback, including materials, error corrections,        *
 * Software Derivatives, enhancements, suggestions and the like that *
 * you provide to IBM relating to the Software (this does not        *
 * include products for which you charge a royalty and distribute to *
 * IBM under other terms and conditions).                            *
 *                                                                   *
 * You agree to distribute the Software and any Software Derivatives *
 * under a license agreement that: 1) is sufficient to notify all    *
 * licensees of the Software and Software Derivatives that IBM       *
 * assumes no liability for any claim that may arise regarding the   *
 * Software or Software Derivatives, and 2) that disclaims all       *
 * warranties, both express and implied, from IBM regarding the      *
 * Software and Software Derivatives.  (If you include this          *
 * Agreement with any distribution of the Software or Software       *
 * Derivatives you will have met this requirement.)  You agree that  *
 * you will not delete any copyright notices in the Software.        *
 *                                                                   *
 * This Agreement is the exclusive statement of your rights in the   *
 * Software as provided by IBM.   Except for the rights granted to   *
 * you in the second paragraph above, You are not granted any other  *
 * patent rights, including but not limited to the right to make     *
 * combinations of the Software with products that infringe IBM      *
 * patents. You agree to comply with all applicable laws and         *
 * regulations, including all export and import laws and regulation. *
 * This Agreement is governed by the laws of the State of New York.  *
 * This Agreement supersedes all other communications,               *
 * understandings or agreements we may have had prior to this        *
 * Agreement.                                                        *
 * ***************************************************************** */

#include <JonahAlg.h>
#include <string.h>

// Algorithm-specific stuff.  This stuff really belongs down in the CDSA CSP, but
// we do it in the misc component since we sometimes need to be able to interrogate
// a key without having ready access to a CSP that implements the algorithm.

static uint32 GetKeySizeRSA(const asn_bitstring & key) {
// This routine was lifted from the KeyWorks CL with minimal changes.
  buffer_t buf;
  uint32 len;
  unsigned char * value;
  uint32 keySize;

  if (key.write(buf)) return 0;

  len = buf.data_len;
  value = buf.data;

  // Now buf contains a RSA public key as specified in PKCS#1 which
        // is a BIT STRING with ASN format
        // RSAPublicKey ::= {
        //    n, INTEGER;
        //    e, INTEGER
        // }
        // e.g
        //    30 81 89        // publicKey = {n, e}
    //       02 81 81     // modulus = n
    //       00 98 1b 4a 2e ...
    //    02 03        // publicExponent = e
    //       01 00 01

        while(len > 1 && *value == 0x00) {
                value ++;
                len --; 
        }

  if(len < 2 || *value != 0x30) return (0);
        value ++;   // *value indicate the length of the sequence or == 81, 82
        len --;

        if(*value < 0x81) { // length value uses one byte
                value ++;
                len --;
        } else if(*value == 0x81) { // length value uses two bytes
                value += 2;
                len -=2;
        } else if(*value == 0x82) {     // length value uses three bytes
                value += 3;
                len -=3;
        } else if(*value == 0x83) {     // length value uses four bytes
                value += 4;
                len -=4;
        } else { // key size is too large
                return (0);
        }

        // *value should be 0x02 (the tag of INTEGER)
        while(len > 1 && *value == 0x00)
        {
                value ++;
                len --;
        }

        if(*value != 0x02 ) return (0);
        value ++;   // *value indicate the number of bytes of the key modulus or == 81, 82
        len --;

        if(*value < 0x81) { // key size uses one byte
                keySize = *value;
        } else if(*value == 0x81) { // key size uses two bytes
                keySize = value[1];
                value ++;
                len --;
        } else if(*value == 0x82) {     // key size uses three bytes
                keySize = value[1]*256 + value[2];              
                value += 2;
                len -= 2;
        } else if(*value == 0x83) {     // key size uses four bytes
                keySize = value[1]*256*256 + value[2]*256 + value[3];           
                value += 3;
                len -= 3;       
        } else {  // key size is too large
                return (0);
        }

        if(len > 1) {
                value ++;
                len --;
        } else {
                if(keySize == 0)
                    return 0;
                else 
                        return (0);
        }

        // Some leading 0 must be deduced from the key size as an integer
        while(len > 1 && *value == 0) {
                value ++;
                len --;
                keySize --;
        }

        keySize *= 8; // convert to bits from bytes
        if(*value < 0x10) keySize -= 4; // the leading four bits of the first byte consists of 0's
// Not sure why we only want 4-bit resolution, but for now this is OK.

        return keySize;

}

static uint32 GetKeySizeDSA(const asn_bitstring & key) {
  return 0;
}

uint32 GetKeySize(const SubjectPublicKeyInfo & key) {

  buffer_t alg_buf;
  uint32 status;
  status = key.algorithm.algorithm.get_value(alg_buf);
  if ((alg_buf.data_len == sizeof(OID_DSA)) 
      && (memcmp(alg_buf.data, OID_DSA, alg_buf.data_len) == 0)) {
// DSA
    return GetKeySizeDSA(key.subjectPublicKey);
  } else if ((alg_buf.data_len == sizeof(OID_RSAwithMD2)) 
             && (memcmp(alg_buf.data, OID_RSAwithMD2, alg_buf.data_len) == 0)) {
// RSAwithMD2
    return GetKeySizeRSA(key.subjectPublicKey);
  } else if ((alg_buf.data_len == sizeof(OID_RSAwithMD4)) 
             && (memcmp(alg_buf.data, OID_RSAwithMD4, alg_buf.data_len) == 0)) {
// RSAwithMD4
    return GetKeySizeRSA(key.subjectPublicKey);
  } else if ((alg_buf.data_len == sizeof(OID_RSAwithMD5)) 
             && (memcmp(alg_buf.data, OID_RSAwithMD5, alg_buf.data_len) == 0)) {
// RSAwithMD5
    return GetKeySizeRSA(key.subjectPublicKey);
  } else if ((alg_buf.data_len == sizeof(OID_RSAwithSHA1)) 
             && (memcmp(alg_buf.data, OID_RSAwithSHA1, alg_buf.data_len) == 0)) {
// RSAwithSHA1
    return GetKeySizeRSA(key.subjectPublicKey);
  } else return 0;
}
