Beispiel #1
0
/**
  Import an RSAPublicKey or RSAPrivateKey [two-prime only, only support >= 1024-bit keys, defined in PKCS #1 v2.1]
  @param in      The packet to import from
  @param inlen   It's length (octets)
  @param key     [out] Destination for newly imported key
  @return CRYPT_OK if successful, upon error allocated memory is freed
*/
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key)
{
   int           err;
   void         *zero;
   unsigned char *tmpbuf=NULL;
   unsigned long tmpbuf_len;

   LTC_ARGCHK(in          != NULL);
   LTC_ARGCHK(key         != NULL);
   LTC_ARGCHK(ltc_mp.name != NULL);

   /* init key */
   if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ,
                            &key->dP, &key->qP, &key->p, &key->q, NULL)) != CRYPT_OK) {
      return err;
   }

   /* see if the OpenSSL DER format RSA public key will work */
   tmpbuf_len = MAX_RSA_SIZE * 8;
   tmpbuf = XCALLOC(1, tmpbuf_len);
   if (tmpbuf == NULL) {
       err = CRYPT_MEM;
       goto LBL_ERR;
   }

   err = der_decode_subject_public_key_info(in, inlen,
        PKA_RSA, tmpbuf, &tmpbuf_len,
        LTC_ASN1_NULL, NULL, 0);

   if (err == CRYPT_OK) { /* SubjectPublicKeyInfo format */

      /* now it should be SEQUENCE { INTEGER, INTEGER } */
      if ((err = der_decode_sequence_multi(tmpbuf, tmpbuf_len,
                                           LTC_ASN1_INTEGER, 1UL, key->N,
                                           LTC_ASN1_INTEGER, 1UL, key->e,
                                           LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         goto LBL_ERR;
      }
      key->type = PK_PUBLIC;
      err = CRYPT_OK;
      goto LBL_FREE;
   }

   /* not SSL public key, try to match against PKCS #1 standards */
   if ((err = der_decode_sequence_multi(in, inlen,
                                  LTC_ASN1_INTEGER, 1UL, key->N,
                                  LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
      goto LBL_ERR;
   }

   if (mp_cmp_d(key->N, 0) == LTC_MP_EQ) {
      if ((err = mp_init(&zero)) != CRYPT_OK) {
         goto LBL_ERR;
      }
      /* it's a private key */
      if ((err = der_decode_sequence_multi(in, inlen,
                          LTC_ASN1_INTEGER, 1UL, zero,
                          LTC_ASN1_INTEGER, 1UL, key->N,
                          LTC_ASN1_INTEGER, 1UL, key->e,
                          LTC_ASN1_INTEGER, 1UL, key->d,
                          LTC_ASN1_INTEGER, 1UL, key->p,
                          LTC_ASN1_INTEGER, 1UL, key->q,
                          LTC_ASN1_INTEGER, 1UL, key->dP,
                          LTC_ASN1_INTEGER, 1UL, key->dQ,
                          LTC_ASN1_INTEGER, 1UL, key->qP,
                          LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         mp_clear(zero);
         goto LBL_ERR;
      }
      mp_clear(zero);
      key->type = PK_PRIVATE;
   } else if (mp_cmp_d(key->N, 1) == LTC_MP_EQ) {
      /* we don't support multi-prime RSA */
      err = CRYPT_PK_INVALID_TYPE;
      goto LBL_ERR;
   } else {
      /* it's a public key and we lack e */
      if ((err = der_decode_sequence_multi(in, inlen,
                                     LTC_ASN1_INTEGER, 1UL, key->N,
                                     LTC_ASN1_INTEGER, 1UL, key->e,
                                     LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         goto LBL_ERR;
      }
      key->type = PK_PUBLIC;
   }
   err = CRYPT_OK;
   goto LBL_FREE;

LBL_ERR:
   mp_clear_multi(key->d,  key->e, key->N, key->dQ, key->dP, key->qP, key->p, key->q, NULL);

LBL_FREE:
   if (tmpbuf != NULL)
     XFREE(tmpbuf);

   return err;
}
Beispiel #2
0
void
i386_init(void)
{
	extern char edata[], end[];

	// Before doing anything else, complete the ELF loading process.
	// Clear the uninitialized global data (BSS) section of our program.
	// This ensures that all static/global variables start out zero.
	memset(edata, 0, end - edata);

	// Initialize the console.
	// Can't call cprintf until after we do this!
	cons_init();

	cprintf("6828 decimal is %o octal!\n", 6828);

	// Lab 2 memory management initialization functions
	mem_init();

	// Lab 3 user environment initialization functions
	env_init();
	trap_init();

	// Lab 4 multiprocessor initialization functions
	mp_init();
	lapic_init();

	// Lab 4 multitasking initialization functions
	pic_init();

	// Lab 6 hardware initialization functions
	time_init();
	pci_init();

	// Acquire the big kernel lock before waking up APs
	// Your code here:
	lock_kernel();
	// Starting non-boot CPUs
	boot_aps();

	// Start fs.
	ENV_CREATE(fs_fs, ENV_TYPE_FS);

#if !defined(TEST_NO_NS)
	// Start ns.
	ENV_CREATE(net_ns, ENV_TYPE_NS);
#endif

#if defined(TEST)
	// Don't touch -- used by grading script!
	ENV_CREATE(TEST, ENV_TYPE_USER);
#else
	// Touch all you want.
	ENV_CREATE(user_icode, ENV_TYPE_USER);
	
#endif // TEST*

	// Should not be necessary - drains keyboard because interrupt has given up.
	kbd_intr();

	// Schedule and run the first user environment!
	sched_yield();
}
Beispiel #3
0
int main(int argc, char *argv[])
{
   int n, tmp;
   long long max;
   mp_int a, b, c, d, e;
#ifdef MTEST_NO_FULLSPEED
   clock_t t1;
#endif
   char buf[4096];

   mp_init(&a);
   mp_init(&b);
   mp_init(&c);
   mp_init(&d);
   mp_init(&e);

   if (argc > 1) {
       max = strtol(argv[1], NULL, 0);
       if (max < 0) {
           if (max > -64) {
               max = (1 << -(max)) + 1;
           } else {
               max = 1;
           }
       } else if (max == 0) {
           max = 1;
       }
   }
   else {
       max = 0;
   }


   /* initial (2^n - 1)^2 testing, makes sure the comba multiplier works [it has the new carry code] */
/*
   mp_set(&a, 1);
   for (n = 1; n < 8192; n++) {
       mp_mul(&a, &a, &c);
       printf("mul\n");
       mp_to64(&a, buf);
       printf("%s\n%s\n", buf, buf);
       mp_to64(&c, buf);
       printf("%s\n", buf);

       mp_add_d(&a, 1, &a);
       mp_mul_2(&a, &a);
       mp_sub_d(&a, 1, &a);
   }
*/

#ifdef LTM_MTEST_REAL_RAND
   rng = fopen("/dev/urandom", "rb");
   if (rng == NULL) {
      rng = fopen("/dev/random", "rb");
      if (rng == NULL) {
         fprintf(stderr, "\nWarning:  stdin used as random source\n\n");
         rng = stdin;
      }
   }
#else
   srand(23);
#endif

#ifdef MTEST_NO_FULLSPEED
   t1 = clock();
#endif
   for (;;) {
#ifdef MTEST_NO_FULLSPEED
      if (clock() - t1 > CLOCKS_PER_SEC) {
         sleep(2);
         t1 = clock();
      }
#endif
       n = getRandChar() % 15;

       if (max != 0) {
           --max;
           if (max == 0)
             n = 255;
       }

   if (n == 0) {
       /* add tests */
       rand_num(&a);
       rand_num(&b);
       mp_add(&a, &b, &c);
       printf("add\n");
       mp_to64(&a, buf);
       printf("%s\n", buf);
       mp_to64(&b, buf);
       printf("%s\n", buf);
       mp_to64(&c, buf);
       printf("%s\n", buf);
   } else if (n == 1) {
      /* sub tests */
       rand_num(&a);
       rand_num(&b);
       mp_sub(&a, &b, &c);
       printf("sub\n");
       mp_to64(&a, buf);
       printf("%s\n", buf);
       mp_to64(&b, buf);
       printf("%s\n", buf);
       mp_to64(&c, buf);
       printf("%s\n", buf);
   } else if (n == 2) {
       /* mul tests */
       rand_num(&a);
       rand_num(&b);
       mp_mul(&a, &b, &c);
       printf("mul\n");
       mp_to64(&a, buf);
       printf("%s\n", buf);
       mp_to64(&b, buf);
       printf("%s\n", buf);
       mp_to64(&c, buf);
       printf("%s\n", buf);
   } else if (n == 3) {
      /* div tests */
       rand_num(&a);
       rand_num(&b);
       mp_div(&a, &b, &c, &d);
       printf("div\n");
       mp_to64(&a, buf);
       printf("%s\n", buf);
       mp_to64(&b, buf);
       printf("%s\n", buf);
       mp_to64(&c, buf);
       printf("%s\n", buf);
       mp_to64(&d, buf);
       printf("%s\n", buf);
   } else if (n == 4) {
      /* sqr tests */
       rand_num(&a);
       mp_sqr(&a, &b);
       printf("sqr\n");
       mp_to64(&a, buf);
       printf("%s\n", buf);
       mp_to64(&b, buf);
       printf("%s\n", buf);
   } else if (n == 5) {
      /* mul_2d test */
      rand_num(&a);
      mp_copy(&a, &b);
      n = getRandChar() & 63;
      mp_mul_2d(&b, n, &b);
      mp_to64(&a, buf);
      printf("mul2d\n");
      printf("%s\n", buf);
      printf("%d\n", n);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 6) {
      /* div_2d test */
      rand_num(&a);
      mp_copy(&a, &b);
      n = getRandChar() & 63;
      mp_div_2d(&b, n, &b, NULL);
      mp_to64(&a, buf);
      printf("div2d\n");
      printf("%s\n", buf);
      printf("%d\n", n);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 7) {
      /* gcd test */
      rand_num(&a);
      rand_num(&b);
      a.sign = MP_ZPOS;
      b.sign = MP_ZPOS;
      mp_gcd(&a, &b, &c);
      printf("gcd\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
      mp_to64(&c, buf);
      printf("%s\n", buf);
   } else if (n == 8) {
      /* lcm test */
      rand_num(&a);
      rand_num(&b);
      a.sign = MP_ZPOS;
      b.sign = MP_ZPOS;
      mp_lcm(&a, &b, &c);
      printf("lcm\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
      mp_to64(&c, buf);
      printf("%s\n", buf);
   } else if (n == 9) {
      /* exptmod test */
      rand_num2(&a);
      rand_num2(&b);
      rand_num2(&c);
//      if (c.dp[0]&1) mp_add_d(&c, 1, &c);
      a.sign = b.sign = c.sign = 0;
      mp_exptmod(&a, &b, &c, &d);
      printf("expt\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
      mp_to64(&c, buf);
      printf("%s\n", buf);
      mp_to64(&d, buf);
      printf("%s\n", buf);
   } else if (n == 10) {
      /* invmod test */
      do {
      rand_num2(&a);
      rand_num2(&b);
      b.sign = MP_ZPOS;
      a.sign = MP_ZPOS;
      mp_gcd(&a, &b, &c);
      } while (mp_cmp_d(&c, 1) != 0 || mp_cmp_d(&b, 1) == 0);
      mp_invmod(&a, &b, &c);
      printf("invmod\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
      mp_to64(&c, buf);
      printf("%s\n", buf);
   } else if (n == 11) {
      rand_num(&a);
      mp_mul_2(&a, &a);
      mp_div_2(&a, &b);
      printf("div2\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 12) {
      rand_num2(&a);
      mp_mul_2(&a, &b);
      printf("mul2\n");
      mp_to64(&a, buf);
      printf("%s\n", buf);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 13) {
      rand_num2(&a);
      tmp = abs(rand()) & THE_MASK;
      mp_add_d(&a, tmp, &b);
      printf("add_d\n");
      mp_to64(&a, buf);
      printf("%s\n%d\n", buf, tmp);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 14) {
      rand_num2(&a);
      tmp = abs(rand()) & THE_MASK;
      mp_sub_d(&a, tmp, &b);
      printf("sub_d\n");
      mp_to64(&a, buf);
      printf("%s\n%d\n", buf, tmp);
      mp_to64(&b, buf);
      printf("%s\n", buf);
   } else if (n == 255) {
      printf("exit\n");
      break;
   }

   }
#ifdef LTM_MTEST_REAL_RAND
   fclose(rng);
#endif
   return 0;
}
Beispiel #4
0
SECStatus 
DH_Derive(SECItem *publicValue, 
          SECItem *prime, 
          SECItem *privateValue, 
          SECItem *derivedSecret, 
          unsigned int outBytes)
{
    mp_int p, Xa, Yb, ZZ, psub1;
    mp_err err = MP_OKAY;
    unsigned int len = 0;
    unsigned int nb;
    unsigned char *secret = NULL;
    if (!publicValue || !prime || !privateValue || !derivedSecret) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    memset(derivedSecret, 0, sizeof *derivedSecret);
    MP_DIGITS(&p)  = 0;
    MP_DIGITS(&Xa) = 0;
    MP_DIGITS(&Yb) = 0;
    MP_DIGITS(&ZZ) = 0;
    MP_DIGITS(&psub1) = 0;
    CHECK_MPI_OK( mp_init(&p)  );
    CHECK_MPI_OK( mp_init(&Xa) );
    CHECK_MPI_OK( mp_init(&Yb) );
    CHECK_MPI_OK( mp_init(&ZZ) );
    CHECK_MPI_OK( mp_init(&psub1) );
    SECITEM_TO_MPINT(*publicValue,  &Yb);
    SECITEM_TO_MPINT(*privateValue, &Xa);
    SECITEM_TO_MPINT(*prime,        &p);
    CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) );

    /* We assume that the modulus, p, is a safe prime. That is, p = 2q+1 where
     * q is also a prime. Thus the orders of the subgroups are factors of 2q:
     * namely 1, 2, q and 2q.
     *
     * We check that the peer's public value isn't zero (which isn't in the
     * group), one (subgroup of order one) or p-1 (subgroup of order 2). We
     * also check that the public value is less than p, to avoid being fooled
     * by values like p+1 or 2*p-1.
     *
     * Thus we must be operating in the subgroup of size q or 2q. */
    if (mp_cmp_d(&Yb, 1) <= 0 ||
	mp_cmp(&Yb, &psub1) >= 0) {
	err = MP_BADARG;
	goto cleanup;
    }

    /* ZZ = (Yb)**Xa mod p */
    CHECK_MPI_OK( mp_exptmod(&Yb, &Xa, &p, &ZZ) );
    /* number of bytes in the derived secret */
    len = mp_unsigned_octet_size(&ZZ);
    if (len <= 0) {
        err = MP_BADARG;
        goto cleanup;
    }

    /*
     * We check to make sure that ZZ is not equal to 1 or -1 mod p.
     * This helps guard against small subgroup attacks, since an attacker
     * using a subgroup of size N will produce 1 or -1 with probability 1/N.
     * When the protocol is executed within a properly large subgroup, the
     * probability of this result will be negligibly small.  For example,
     * with a strong prime of the form 2p+1, the probability will be 1/p.
     *
     * We return MP_BADARG because this is probably the result of a bad
     * public value or a bad prime having been provided.
     */
    if (mp_cmp_d(&ZZ, 1) == 0 ||
        mp_cmp(&ZZ, &psub1) == 0) {
        err = MP_BADARG;
        goto cleanup;
    }

    /* allocate a buffer which can hold the entire derived secret. */
    secret = PORT_Alloc(len);
    if (secret == NULL) {
	err = MP_MEM;
	goto cleanup;
    }
    /* grab the derived secret */
    err = mp_to_unsigned_octets(&ZZ, secret, len);
    if (err >= 0) err = MP_OKAY;
    /* 
    ** if outBytes is 0 take all of the bytes from the derived secret.
    ** if outBytes is not 0 take exactly outBytes from the derived secret, zero
    ** pad at the beginning if necessary, and truncate beginning bytes 
    ** if necessary.
    */
    if (outBytes > 0)
	nb = outBytes;
    else
	nb = len;
    if (SECITEM_AllocItem(NULL, derivedSecret, nb)  == NULL) {
	err = MP_MEM;
	goto cleanup;
    }
    if (len < nb) {
	unsigned int offset = nb - len;
	memset(derivedSecret->data, 0, offset);
	memcpy(derivedSecret->data + offset, secret, len);
    } else {
	memcpy(derivedSecret->data, secret + len - nb, nb);
    }
cleanup:
    mp_clear(&p);
    mp_clear(&Xa);
    mp_clear(&Yb);
    mp_clear(&ZZ);
    mp_clear(&psub1);
    if (secret) {
	/* free the buffer allocated for the full secret. */
	PORT_ZFree(secret, len);
    }
    if (err) {
	MP_TO_SEC_ERROR(err);
	if (derivedSecret->data) 
	    PORT_ZFree(derivedSecret->data, derivedSecret->len);
	return SECFailure;
    }
    return SECSuccess;
}
Beispiel #5
0
SECStatus 
DH_GenParam(int primeLen, DHParams **params)
{
    PLArenaPool *arena;
    DHParams *dhparams;
    unsigned char *pb = NULL;
    unsigned char *ab = NULL;
    unsigned long counter = 0;
    mp_int p, q, a, h, psub1, test;
    mp_err err = MP_OKAY;
    SECStatus rv = SECSuccess;
    if (!params || primeLen < 0) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    if (!arena) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return SECFailure;
    }
    dhparams = (DHParams *)PORT_ArenaZAlloc(arena, sizeof(DHParams));
    if (!dhparams) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	PORT_FreeArena(arena, PR_TRUE);
	return SECFailure;
    }
    dhparams->arena = arena;
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&q) = 0;
    MP_DIGITS(&a) = 0;
    MP_DIGITS(&h) = 0;
    MP_DIGITS(&psub1) = 0;
    MP_DIGITS(&test) = 0;
    CHECK_MPI_OK( mp_init(&p) );
    CHECK_MPI_OK( mp_init(&q) );
    CHECK_MPI_OK( mp_init(&a) );
    CHECK_MPI_OK( mp_init(&h) );
    CHECK_MPI_OK( mp_init(&psub1) );
    CHECK_MPI_OK( mp_init(&test) );
    /* generate prime with MPI, uses Miller-Rabin to generate strong prime. */
    pb = PORT_Alloc(primeLen);
    CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(pb, primeLen) );
    pb[0]          |= 0x80; /* set high-order bit */
    pb[primeLen-1] |= 0x01; /* set low-order bit  */
    CHECK_MPI_OK( mp_read_unsigned_octets(&p, pb, primeLen) );
    CHECK_MPI_OK( mpp_make_prime(&p, primeLen * 8, PR_TRUE, &counter) );
    /* construct Sophie-Germain prime q = (p-1)/2. */
    CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) );
    CHECK_MPI_OK( mp_div_2(&psub1, &q)    );
    /* construct a generator from the prime. */
    ab = PORT_Alloc(primeLen);
    /* generate a candidate number a in p's field */
    CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(ab, primeLen) );
    CHECK_MPI_OK( mp_read_unsigned_octets(&a, ab, primeLen) );
    /* force a < p (note that quot(a/p) <= 1) */
    if ( mp_cmp(&a, &p) > 0 )
	CHECK_MPI_OK( mp_sub(&a, &p, &a) );
    do {
	/* check that a is in the range [2..p-1] */
	if ( mp_cmp_d(&a, 2) < 0 || mp_cmp(&a, &psub1) >= 0) {
	    /* a is outside of the allowed range.  Set a=3 and keep going. */
            mp_set(&a, 3);
	}
	/* if a**q mod p != 1 then a is a generator */
	CHECK_MPI_OK( mp_exptmod(&a, &q, &p, &test) );
	if ( mp_cmp_d(&test, 1) != 0 )
	    break;
	/* increment the candidate and try again. */
	CHECK_MPI_OK( mp_add_d(&a, 1, &a) );
    } while (PR_TRUE);
    MPINT_TO_SECITEM(&p, &dhparams->prime, arena);
    MPINT_TO_SECITEM(&a, &dhparams->base, arena);
    *params = dhparams;
cleanup:
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&a);
    mp_clear(&h);
    mp_clear(&psub1);
    mp_clear(&test);
    if (pb) PORT_ZFree(pb, primeLen);
    if (ab) PORT_ZFree(ab, primeLen);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    if (rv)
	PORT_FreeArena(arena, PR_TRUE);
    return rv;
}
Beispiel #6
0
void TASK_Micropython (void *pvParameters) {
    // initialize the garbage collector with the top of our stack
    uint32_t sp = gc_helper_get_sp();
    gc_collect_init (sp);

    bool safeboot = false;
    mptask_pre_init();

#ifndef DEBUG
    safeboot = PRCMGetSpecialBit(PRCM_SAFE_BOOT_BIT);
#endif

soft_reset:

    // GC init
    gc_init(&_boot, &_eheap);

    // MicroPython init
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_init(mp_sys_argv, 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)

    // execute all basic initializations
    mpexception_init0();
    mp_irq_init0();
    pyb_sleep_init0();
    pin_init0();
    mperror_init0();
    uart_init0();
    timer_init0();
    readline_init0();
    mod_network_init0();
    moduos_init0();
    rng_init0();

    pybsleep_reset_cause_t rstcause = pyb_sleep_get_reset_cause();
    if (rstcause < PYB_SLP_SOFT_RESET) {
        if (rstcause == PYB_SLP_HIB_RESET) {
            // when waking up from hibernate we just want
            // to enable simplelink and leave it as is
            wlan_first_start();
        }
        else {
            // only if not comming out of hibernate or a soft reset
            mptask_enter_ap_mode();
        }

        // enable telnet and ftp
        servers_start();
    }

    // initialize the serial flash file system
    mptask_init_sflash_filesystem();

    // append the flash paths to the system path
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash));
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash_slash_lib));

    // reset config variables; they should be set by boot.py
    MP_STATE_PORT(machine_config_main) = MP_OBJ_NULL;

    if (!safeboot) {
        // run boot.py
        int ret = pyexec_file("boot.py");
        if (ret & PYEXEC_FORCED_EXIT) {
            goto soft_reset_exit;
        }
        if (!ret) {
            // flash the system led
            mperror_signal_error();
        }
    }

    // now we initialise sub-systems that need configuration from boot.py,
    // or whose initialisation can be safely deferred until after running
    // boot.py.

    // at this point everything is fully configured and initialised.

    if (!safeboot) {
        // run the main script from the current directory.
        if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
            const char *main_py;
            if (MP_STATE_PORT(machine_config_main) == MP_OBJ_NULL) {
                main_py = "main.py";
            } else {
                main_py = mp_obj_str_get_str(MP_STATE_PORT(machine_config_main));
            }
            int ret = pyexec_file(main_py);
            if (ret & PYEXEC_FORCED_EXIT) {
                goto soft_reset_exit;
            }
            if (!ret) {
                // flash the system led
                mperror_signal_error();
            }
        }
    }

    // main script is finished, so now go into REPL mode.
    // the REPL mode can change, or it can request a soft reset.
    for ( ; ; ) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }

soft_reset_exit:

    // soft reset
    pyb_sleep_signal_soft_reset();
    mp_printf(&mp_plat_print, "PYB: soft reboot\n");

    // disable all callbacks to avoid undefined behaviour
    // when coming out of a soft reset
    mp_irq_disable_all();

    // cancel the RTC alarm which might be running independent of the irq state
    pyb_rtc_disable_alarm();

    // flush the serial flash buffer
    sflash_disk_flush();

    // clean-up the user socket space
    modusocket_close_all_user_sockets();

    // wait for pending transactions to complete
    mp_hal_delay_ms(20);

    goto soft_reset;
}
Beispiel #7
0
int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
{
  mp_int  M[TAB_SIZE], res;
  mp_digit buf, mp;
  int     err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;

  /* use a pointer to the reduction algorithm.  This allows us to use
   * one of many reduction algorithms without modding the guts of
   * the code with if statements everywhere.
   */
  int     (*redux)(mp_int*,mp_int*,mp_digit);

  /* find window size */
  x = mp_count_bits (X);
  if (x <= 7) {
    winsize = 2;
  } else if (x <= 36) {
    winsize = 3;
  } else if (x <= 140) {
    winsize = 4;
  } else if (x <= 450) {
    winsize = 5;
  } else if (x <= 1303) {
    winsize = 6;
  } else if (x <= 3529) {
    winsize = 7;
  } else {
    winsize = 8;
  }

#ifdef MP_LOW_MEM
  if (winsize > 5) {
     winsize = 5;
  }
#endif

  /* init M array */
  /* init first cell */
  if ((err = mp_init(&M[1])) != MP_OKAY) {
     return err;
  }

  /* now init the second half of the array */
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
    if ((err = mp_init(&M[x])) != MP_OKAY) {
      for (y = 1<<(winsize-1); y < x; y++) {
        mp_clear (&M[y]);
      }
      mp_clear(&M[1]);
      return err;
    }
  }

  /* determine and setup reduction code */
  if (redmode == 0) {
#ifdef BN_MP_MONTGOMERY_SETUP_C     
     /* now setup montgomery  */
     if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
        goto LBL_M;
     }
#else
     err = MP_VAL;
     goto LBL_M;
#endif

     /* automatically pick the comba one if available (saves quite a few calls/ifs) */
#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
     if (((P->used * 2 + 1) < MP_WARRAY) &&
          P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
        redux = fast_mp_montgomery_reduce;
     } else 
#endif
     {
#ifdef BN_MP_MONTGOMERY_REDUCE_C
        /* use slower baseline Montgomery method */
        redux = mp_montgomery_reduce;
#else
        err = MP_VAL;
        goto LBL_M;
#endif
     }
  } else if (redmode == 1) {
#if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
     /* setup DR reduction for moduli of the form B**k - b */
     mp_dr_setup(P, &mp);
     redux = mp_dr_reduce;
#else
     err = MP_VAL;
     goto LBL_M;
#endif
  } else {
#if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
     /* setup DR reduction for moduli of the form 2**k - b */
     if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
        goto LBL_M;
     }
     redux = mp_reduce_2k;
#else
     err = MP_VAL;
     goto LBL_M;
#endif
  }

  /* setup result */
  if ((err = mp_init (&res)) != MP_OKAY) {
    goto LBL_M;
  }

  /* create M table
   *

   *
   * The first half of the table is not computed though accept for M[0] and M[1]
   */

  if (redmode == 0) {
#ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
     /* now we need R mod m */
     if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
       goto LBL_RES;
     }
#else 
     err = MP_VAL;
     goto LBL_RES;
#endif

     /* now set M[1] to G * R mod m */
     if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
       goto LBL_RES;
     }
  } else {
     mp_set(&res, 1);
     if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
        goto LBL_RES;
     }
  }

  /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
  if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
    goto LBL_RES;
  }

  for (x = 0; x < (winsize - 1); x++) {
    if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
      goto LBL_RES;
    }
    if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
      goto LBL_RES;
    }
  }

  /* create upper table */
  for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
    if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
      goto LBL_RES;
    }
    if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
      goto LBL_RES;
    }
  }

  /* set initial mode and bit cnt */
  mode   = 0;
  bitcnt = 1;
  buf    = 0;
  digidx = X->used - 1;
  bitcpy = 0;
  bitbuf = 0;

  for (;;) {
    /* grab next digit as required */
    if (--bitcnt == 0) {
      /* if digidx == -1 we are out of digits so break */
      if (digidx == -1) {
        break;
      }
      /* read next digit and reset bitcnt */
      buf    = X->dp[digidx--];
      bitcnt = (int)DIGIT_BIT;
    }

    /* grab the next msb from the exponent */
    y     = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
    buf <<= (mp_digit)1;

    /* if the bit is zero and mode == 0 then we ignore it
     * These represent the leading zero bits before the first 1 bit
     * in the exponent.  Technically this opt is not required but it
     * does lower the # of trivial squaring/reductions used
     */
    if (mode == 0 && y == 0) {
      continue;
    }

    /* if the bit is zero and mode == 1 then we square */
    if (mode == 1 && y == 0) {
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
        goto LBL_RES;
      }
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
        goto LBL_RES;
      }
      continue;
    }

    /* else we add it to the window */
    bitbuf |= (y << (winsize - ++bitcpy));
    mode    = 2;

    if (bitcpy == winsize) {
      /* ok window is filled so square as required and multiply  */
      /* square first */
      for (x = 0; x < winsize; x++) {
        if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
          goto LBL_RES;
        }
        if ((err = redux (&res, P, mp)) != MP_OKAY) {
          goto LBL_RES;
        }
      }

      /* then multiply */
      if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
        goto LBL_RES;
      }
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
        goto LBL_RES;
      }

      /* empty window and reset */
      bitcpy = 0;
      bitbuf = 0;
      mode   = 1;
    }
  }

  /* if bits remain then square/multiply */
  if (mode == 2 && bitcpy > 0) {
    /* square then multiply if the bit is set */
    for (x = 0; x < bitcpy; x++) {
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
        goto LBL_RES;
      }
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
        goto LBL_RES;
      }

      /* get next bit of the window */
      bitbuf <<= 1;
      if ((bitbuf & (1 << winsize)) != 0) {
        /* then multiply */
        if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
          goto LBL_RES;
        }
        if ((err = redux (&res, P, mp)) != MP_OKAY) {
          goto LBL_RES;
        }
      }
    }
  }

  if (redmode == 0) {
     /* fixup result if Montgomery reduction is used
      * recall that any value in a Montgomery system is
      * actually multiplied by R mod n.  So we have
      * to reduce one more time to cancel out the factor
      * of R.
      */
     if ((err = redux(&res, P, mp)) != MP_OKAY) {
       goto LBL_RES;
     }
  }

  /* swap res with Y */
  mp_exch (&res, Y);
  err = MP_OKAY;
LBL_RES:mp_clear (&res);
LBL_M:
  mp_clear(&M[1]);
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
    mp_clear (&M[x]);
  }
  return err;
}
Beispiel #8
0
static SECStatus
get_blinding_params(RSAPrivateKey *key, mp_int *n, unsigned int modLen,
                    mp_int *f, mp_int *g)
{
    RSABlindingParams *rsabp           = NULL;
    blindingParams    *bpUnlinked      = NULL;
    blindingParams    *bp, *prevbp     = NULL;
    PRCList           *el;
    SECStatus          rv              = SECSuccess;
    mp_err             err             = MP_OKAY;
    int                cmp             = -1;
    PRBool             holdingLock     = PR_FALSE;

    do {
	if (blindingParamsList.lock == NULL) {
	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
	    return SECFailure;
	}
	/* Acquire the list lock */
	PZ_Lock(blindingParamsList.lock);
	holdingLock = PR_TRUE;

	/* Walk the list looking for the private key */
	for (el = PR_NEXT_LINK(&blindingParamsList.head);
	     el != &blindingParamsList.head;
	     el = PR_NEXT_LINK(el)) {
	    rsabp = (RSABlindingParams *)el;
	    cmp = SECITEM_CompareItem(&rsabp->modulus, &key->modulus);
	    if (cmp >= 0) {
		/* The key is found or not in the list. */
		break;
	    }
	}

	if (cmp) {
	    /* At this point, the key is not in the list.  el should point to 
	    ** the list element before which this key should be inserted. 
	    */
	    rsabp = PORT_ZNew(RSABlindingParams);
	    if (!rsabp) {
		PORT_SetError(SEC_ERROR_NO_MEMORY);
		goto cleanup;
	    }

	    rv = init_blinding_params(rsabp, key, n, modLen);
	    if (rv != SECSuccess) {
		PORT_ZFree(rsabp, sizeof(RSABlindingParams));
		goto cleanup;
	    }

	    /* Insert the new element into the list
	    ** If inserting in the middle of the list, el points to the link
	    ** to insert before.  Otherwise, the link needs to be appended to
	    ** the end of the list, which is the same as inserting before the
	    ** head (since el would have looped back to the head).
	    */
	    PR_INSERT_BEFORE(&rsabp->link, el);
	}

	/* We've found (or created) the RSAblindingParams struct for this key.
	 * Now, search its list of ready blinding params for a usable one.
	 */
	while (0 != (bp = rsabp->bp)) {
	    if (--(bp->counter) > 0) {
		/* Found a match and there are still remaining uses left */
		/* Return the parameters */
		CHECK_MPI_OK( mp_copy(&bp->f, f) );
		CHECK_MPI_OK( mp_copy(&bp->g, g) );

		PZ_Unlock(blindingParamsList.lock); 
		return SECSuccess;
	    }
	    /* exhausted this one, give its values to caller, and
	     * then retire it.
	     */
	    mp_exch(&bp->f, f);
	    mp_exch(&bp->g, g);
	    mp_clear( &bp->f );
	    mp_clear( &bp->g );
	    bp->counter = 0;
	    /* Move to free list */
	    rsabp->bp   = bp->next;
	    bp->next    = rsabp->free;
	    rsabp->free = bp;
	    /* In case there're threads waiting for new blinding
	     * value - notify 1 thread the value is ready
	     */
	    if (blindingParamsList.waitCount > 0) {
		PR_NotifyCondVar( blindingParamsList.cVar );
		blindingParamsList.waitCount--;
	    }
	    PZ_Unlock(blindingParamsList.lock); 
	    return SECSuccess;
	}
	/* We did not find a usable set of blinding params.  Can we make one? */
	/* Find a free bp struct. */
	prevbp = NULL;
	if ((bp = rsabp->free) != NULL) {
	    /* unlink this bp */
	    rsabp->free  = bp->next;
	    bp->next     = NULL;
	    bpUnlinked   = bp;  /* In case we fail */

	    PZ_Unlock(blindingParamsList.lock); 
	    holdingLock = PR_FALSE;
	    /* generate blinding parameter values for the current thread */
	    CHECK_SEC_OK( generate_blinding_params(key, f, g, n, modLen ) );

	    /* put the blinding parameter values into cache */
	    CHECK_MPI_OK( mp_init( &bp->f) );
	    CHECK_MPI_OK( mp_init( &bp->g) );
	    CHECK_MPI_OK( mp_copy( f, &bp->f) );
	    CHECK_MPI_OK( mp_copy( g, &bp->g) );

	    /* Put this at head of queue of usable params. */
	    PZ_Lock(blindingParamsList.lock);
	    holdingLock = PR_TRUE;
	    /* initialize RSABlindingParamsStr */
	    bp->counter = RSA_BLINDING_PARAMS_MAX_REUSE;
	    bp->next    = rsabp->bp;
	    rsabp->bp   = bp;
	    bpUnlinked  = NULL;
	    /* In case there're threads waiting for new blinding value
	     * just notify them the value is ready
	     */
	    if (blindingParamsList.waitCount > 0) {
		PR_NotifyAllCondVar( blindingParamsList.cVar );
		blindingParamsList.waitCount = 0;
	    }
	    PZ_Unlock(blindingParamsList.lock);
	    return SECSuccess;
	}
	/* Here, there are no usable blinding parameters available,
	 * and no free bp blocks, presumably because they're all 
	 * actively having parameters generated for them.
	 * So, we need to wait here and not eat up CPU until some 
	 * change happens. 
	 */
	blindingParamsList.waitCount++;
	PR_WaitCondVar( blindingParamsList.cVar, PR_INTERVAL_NO_TIMEOUT );
	PZ_Unlock(blindingParamsList.lock); 
	holdingLock = PR_FALSE;
    } while (1);

cleanup:
    /* It is possible to reach this after the lock is already released.  */
    if (bpUnlinked) {
	if (!holdingLock) {
	    PZ_Lock(blindingParamsList.lock);
	    holdingLock = PR_TRUE;
	}
	bp = bpUnlinked;
	mp_clear( &bp->f );
	mp_clear( &bp->g );
	bp->counter = 0;
    	/* Must put the unlinked bp back on the free list */
	bp->next    = rsabp->free;
	rsabp->free = bp;
    }
    if (holdingLock) {
	PZ_Unlock(blindingParamsList.lock);
	holdingLock = PR_FALSE;
    }
    if (err) {
	MP_TO_SEC_ERROR(err);
    }
    return SECFailure;
}
Beispiel #9
0
/*
** Perform a raw private-key operation 
**	Length of input and output buffers are equal to key's modulus len.
*/
static SECStatus 
rsa_PrivateKeyOp(RSAPrivateKey *key, 
                 unsigned char *output, 
                 const unsigned char *input,
                 PRBool check)
{
    unsigned int modLen;
    unsigned int offset;
    SECStatus rv = SECSuccess;
    mp_err err;
    mp_int n, c, m;
    mp_int f, g;
    if (!key || !output || !input) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    /* check input out of range (needs to be in range [0..n-1]) */
    modLen = rsa_modulusLen(&key->modulus);
    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    MP_DIGITS(&n) = 0;
    MP_DIGITS(&c) = 0;
    MP_DIGITS(&m) = 0;
    MP_DIGITS(&f) = 0;
    MP_DIGITS(&g) = 0;
    CHECK_MPI_OK( mp_init(&n) );
    CHECK_MPI_OK( mp_init(&c) );
    CHECK_MPI_OK( mp_init(&m) );
    CHECK_MPI_OK( mp_init(&f) );
    CHECK_MPI_OK( mp_init(&g) );
    SECITEM_TO_MPINT(key->modulus, &n);
    OCTETS_TO_MPINT(input, &c, modLen);
    /* If blinding, compute pre-image of ciphertext by multiplying by
    ** blinding factor
    */
    if (nssRSAUseBlinding) {
	CHECK_SEC_OK( get_blinding_params(key, &n, modLen, &f, &g) );
	/* c' = c*f mod n */
	CHECK_MPI_OK( mp_mulmod(&c, &f, &n, &c) );
    }
    /* Do the private key operation m = c**d mod n */
    if ( key->prime1.len      == 0 ||
         key->prime2.len      == 0 ||
         key->exponent1.len   == 0 ||
         key->exponent2.len   == 0 ||
         key->coefficient.len == 0) {
	CHECK_SEC_OK( rsa_PrivateKeyOpNoCRT(key, &m, &c, &n, modLen) );
    } else if (check) {
	CHECK_SEC_OK( rsa_PrivateKeyOpCRTCheckedPubKey(key, &m, &c) );
    } else {
	CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, &m, &c) );
    }
    /* If blinding, compute post-image of plaintext by multiplying by
    ** blinding factor
    */
    if (nssRSAUseBlinding) {
	/* m = m'*g mod n */
	CHECK_MPI_OK( mp_mulmod(&m, &g, &n, &m) );
    }
    err = mp_to_fixlen_octets(&m, output, modLen);
    if (err >= 0) err = MP_OKAY;
cleanup:
    mp_clear(&n);
    mp_clear(&c);
    mp_clear(&m);
    mp_clear(&f);
    mp_clear(&g);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    return rv;
}
void
i386_init(void)
{
    /* __asm __volatile("int $12"); */

	extern char edata[], end[];
	int num = 0, res;

	// Before doing anything else, complete the ELF loading process.
	// Clear the uninitialized global data (BSS) section of our program.
	// This ensures that all static/global variables start out zero.
	memset(edata, 0, end - edata);

	// Initialize the console.
	// Can't call cprintf until after we do this!
	cons_init();

	cprintf("6828 decimal is %o octal!\n", 6828);

#ifdef VMM_GUEST
	/* Guest VMX extension exposure check */
	{
		uint32_t ecx = 0;
		cpuid(0x1, NULL, NULL, &ecx, NULL);
		if (ecx & 0x20)
			panic("[ERR] VMX extension exposed to guest.\n");
		else
			cprintf("VMX extension hidden from guest.\n");
	}
#endif

#ifndef VMM_GUEST
    extern char end[];
    end_debug = read_section_headers((0x10000+KERNBASE), (uintptr_t)end); 
#endif

	// Lab 2 memory management initialization functions
	x64_vm_init();

	// Lab 3 user environment initialization functions
	env_init();
	trap_init();
	//test_traps();

#ifndef VMM_GUEST
	// Lab 4 multiprocessor initialization functions
	mp_init();
	lapic_init();
#endif

	// Lab 4 multitasking initialization functions
	pic_init();

	// Lab 6 hardware initialization functions
	time_init();
	pci_init();

	// Acquire the big kernel lock before waking up APs
	// Your code here:

#ifndef VMM_GUEST
	// Starting non-boot CPUs
	//boot_aps();
#endif

	// Should always have idle processes at first.
	int i;
	for (i = 0; i < NCPU; i++)
		ENV_CREATE(user_idle, ENV_TYPE_IDLE);
	// Start fs.
	ENV_CREATE(fs_fs, ENV_TYPE_FS);
    ENV_CREATE(net_ns, ENV_TYPE_NS);
	//ENV_CREATE(user_testfile, ENV_TYPE_USER);

#if defined(TEST)
	// Don't touch -- used by grading script!
	ENV_CREATE(TEST, ENV_TYPE_USER);
#else
	// Touch all you want.
#if defined(TEST_EPT_MAP)
	test_ept_map();
#endif
	//ENV_CREATE(user_httpd, ENV_TYPE_USER);
	ENV_CREATE(user_icode, ENV_TYPE_USER);
	//ENV_CREATE(user_forktree, ENV_TYPE_USER);
	//ENV_CREATE(user_buggyhello, ENV_TYPE_USER);
#endif // TEST*

	// Should not be necessary - drains keyboard because interrupt has given up.
	kbd_intr();
	cprintf("Running first environment");
	// Schedule and run the first user environment!
	sched_yield();
}
Beispiel #11
0
int
is_mersenne (long s, int *pp)
{
  mp_int  n, u;
  int     res, k;
  
  *pp = 0;

  if ((res = mp_init (&n)) != MP_OKAY) {
    return res;
  }

  if ((res = mp_init (&u)) != MP_OKAY) {
    goto LBL_N;
  }

  /* n = 2^s - 1 */
  if ((res = mp_2expt(&n, s)) != MP_OKAY) {
     goto LBL_MU;
  }
  if ((res = mp_sub_d (&n, 1, &n)) != MP_OKAY) {
    goto LBL_MU;
  }

  /* set u=4 */
  mp_set (&u, 4);

  /* for k=1 to s-2 do */
  for (k = 1; k <= s - 2; k++) {
    /* u = u^2 - 2 mod n */
    if ((res = mp_sqr (&u, &u)) != MP_OKAY) {
      goto LBL_MU;
    }
    if ((res = mp_sub_d (&u, 2, &u)) != MP_OKAY) {
      goto LBL_MU;
    }

    /* make sure u is positive */
    while (u.sign == MP_NEG) {
      if ((res = mp_add (&u, &n, &u)) != MP_OKAY) {
         goto LBL_MU;
      }
    }

    /* reduce */
    if ((res = mp_reduce_2k (&u, &n, 1)) != MP_OKAY) {
      goto LBL_MU;
    }
  }

  /* if u == 0 then its prime */
  if (mp_iszero (&u) == 1) {
    mp_prime_is_prime(&n, 8, pp);
  if (*pp != 1) printf("FAILURE\n");
  }

  res = MP_OKAY;
LBL_MU:mp_clear (&u);
LBL_N:mp_clear (&n);
  return res;
}
Beispiel #12
0
void TASK_Micropython (void *pvParameters) {
    // initialize the garbage collector with the top of our stack
    uint32_t sp = gc_helper_get_sp();
    gc_collect_init (sp);

    bool safeboot = false;
    mptask_pre_init();

#ifndef DEBUG
    safeboot = PRCMGetSpecialBit(PRCM_SAFE_BOOT_BIT);
#endif

soft_reset:

    // GC init
    gc_init(&_boot, &_eheap);

    // MicroPython init
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_init(mp_sys_argv, 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)

    // execute all basic initializations
    mpexception_init0();
    mpcallback_init0();
    pybsleep_init0();
    mperror_init0();
    uart_init0();
    pin_init0();
    timer_init0();
    readline_init0();
    mod_network_init0();
#if MICROPY_HW_ENABLE_RNG
    rng_init0();
#endif

#ifdef LAUNCHXL
    // configure the stdio uart pins with the correct alternate functions
    // param 3 ("mode") is DON'T CARE" for AFs others than GPIO
    pin_config ((pin_obj_t *)&MICROPY_STDIO_UART_TX_PIN, MICROPY_STDIO_UART_TX_PIN_AF, 0, PIN_TYPE_STD_PU, PIN_STRENGTH_2MA);
    pin_config ((pin_obj_t *)&MICROPY_STDIO_UART_RX_PIN, MICROPY_STDIO_UART_RX_PIN_AF, 0, PIN_TYPE_STD_PU, PIN_STRENGTH_2MA);
    // instantiate the stdio uart
    mp_obj_t args[2] = {
            mp_obj_new_int(MICROPY_STDIO_UART),
            mp_obj_new_int(MICROPY_STDIO_UART_BAUD),
    };
    pyb_stdio_uart = pyb_uart_type.make_new((mp_obj_t)&pyb_uart_type, MP_ARRAY_SIZE(args), 0, args);
    // create a callback for the uart, in order to enable the rx interrupts
    uart_callback_new (pyb_stdio_uart, mp_const_none, MICROPY_STDIO_UART_RX_BUF_SIZE, INT_PRIORITY_LVL_3);
#else
    pyb_stdio_uart = MP_OBJ_NULL;
#endif

    pybsleep_reset_cause_t rstcause = pybsleep_get_reset_cause();
    if (rstcause < PYB_SLP_SOFT_RESET) {
        if (rstcause == PYB_SLP_HIB_RESET) {
            // when waking up from hibernate we just want
            // to enable simplelink and leave it as is
            wlan_first_start();
        }
        else {
            // only if not comming out of hibernate or a soft reset
            mptask_enter_ap_mode();
        }

        // enable telnet and ftp
        servers_start();
    }

    // initialize the serial flash file system
    mptask_init_sflash_filesystem();

    // append the flash paths to the system path
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash));
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash_slash_lib));

    // reset config variables; they should be set by boot.py
    MP_STATE_PORT(pyb_config_main) = MP_OBJ_NULL;

    if (!safeboot) {
        // run boot.py
        int ret = pyexec_file("boot.py");
        if (ret & PYEXEC_FORCED_EXIT) {
            goto soft_reset_exit;
        }
        if (!ret) {
            // flash the system led
            mperror_signal_error();
        }
    }

    // now we initialise sub-systems that need configuration from boot.py,
    // or whose initialisation can be safely deferred until after running
    // boot.py.

    // at this point everything is fully configured and initialised.

    if (!safeboot) {
        // run the main script from the current directory.
        if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
            const char *main_py;
            if (MP_STATE_PORT(pyb_config_main) == MP_OBJ_NULL) {
                main_py = "main.py";
            } else {
                main_py = mp_obj_str_get_str(MP_STATE_PORT(pyb_config_main));
            }
            int ret = pyexec_file(main_py);
            if (ret & PYEXEC_FORCED_EXIT) {
                goto soft_reset_exit;
            }
            if (!ret) {
                // flash the system led
                mperror_signal_error();
            }
        }
    }

    // main script is finished, so now go into REPL mode.
    // the REPL mode can change, or it can request a soft reset.
    for ( ; ; ) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }

soft_reset_exit:

    // soft reset
    pybsleep_signal_soft_reset();
    mp_printf(&mp_plat_print, "PYB: soft reboot\n");

    // disable all peripherals that could trigger a callback
    pyb_rtc_callback_disable(NULL);
    timer_disable_all();
    uart_disable_all();

    // flush the serial flash buffer
    sflash_disk_flush();

    // clean-up the user socket space
    modusocket_close_all_user_sockets();

#if MICROPY_HW_HAS_SDCARD
    pybsd_disable();
#endif

    // wait for pending transactions to complete
    HAL_Delay(20);

    goto soft_reset;
}
Beispiel #13
0
/* this is a shell function that calls either the normal or Montgomery
 * exptmod functions.  Originally the call to the montgomery code was
 * embedded in the normal function but that wasted alot of stack space
 * for nothing (since 99% of the time the Montgomery code would be called)
 */
int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
{
  int dr;

  /* modulus P must be positive */
  if (P->sign == MP_NEG) {
     return MP_VAL;
  }

  /* if exponent X is negative we have to recurse */
  if (X->sign == MP_NEG) {
#ifdef BN_MP_INVMOD_C
     mp_int tmpG, tmpX;
     int err;

     /* first compute 1/G mod P */
     if ((err = mp_init(&tmpG)) != MP_OKAY) {
        return err;
     }
     if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
        mp_clear(&tmpG);
        return err;
     }

     /* now get |X| */
     if ((err = mp_init(&tmpX)) != MP_OKAY) {
        mp_clear(&tmpG);
        return err;
     }
     if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
        mp_clear_multi(&tmpG, &tmpX, NULL);
        return err;
     }

     /* and now compute (1/G)**|X| instead of G**X [X < 0] */
     err = mp_exptmod(&tmpG, &tmpX, P, Y);
     mp_clear_multi(&tmpG, &tmpX, NULL);
     return err;
#else 
     /* no invmod */
     return MP_VAL;
#endif
  }

/* modified diminished radix reduction */
#if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
  if (mp_reduce_is_2k_l(P) == MP_YES) {
     return s_mp_exptmod(G, X, P, Y, 1);
  }
#endif

#ifdef BN_MP_DR_IS_MODULUS_C
  /* is it a DR modulus? */
  dr = mp_dr_is_modulus(P);
#else
  /* default to no */
  dr = 0;
#endif

#ifdef BN_MP_REDUCE_IS_2K_C
  /* if not, is it a unrestricted DR modulus? */
  if (dr == 0) {
     dr = mp_reduce_is_2k(P) << 1;
  }
#endif
    
  /* if the modulus is odd or dr != 0 use the montgomery method */
#ifdef BN_MP_EXPTMOD_FAST_C
  if (mp_isodd (P) == 1 || dr !=  0) {
    return mp_exptmod_fast (G, X, P, Y, dr);
  } else {
#endif
#ifdef BN_S_MP_EXPTMOD_C
    /* otherwise use the generic Barrett reduction technique */
    return s_mp_exptmod (G, X, P, Y, 0);
#else
    /* no exptmod for evens */
    return MP_VAL;
#endif
#ifdef BN_MP_EXPTMOD_FAST_C
  }
#endif
}
Beispiel #14
0
/* makes a prime of at least k bits */
int
pprime (int k, int li, mp_int * p, mp_int * q)
{
  mp_int  a, b, c, n, x, y, z, v;
  int     res, ii;
  static const mp_digit bases[] = { 2, 3, 5, 7, 11, 13, 17, 19 };

  /* single digit ? */
  if (k <= (int) DIGIT_BIT) {
    mp_set (p, prime_digit ());
    return MP_OKAY;
  }

  if ((res = mp_init (&c)) != MP_OKAY) {
    return res;
  }

  if ((res = mp_init (&v)) != MP_OKAY) {
    goto LBL_C;
  }

  /* product of first 50 primes */
  if ((res =
       mp_read_radix (&v,
		      "19078266889580195013601891820992757757219839668357012055907516904309700014933909014729740190",
		      10)) != MP_OKAY) {
    goto LBL_V;
  }

  if ((res = mp_init (&a)) != MP_OKAY) {
    goto LBL_V;
  }

  /* set the prime */
  mp_set (&a, prime_digit ());

  if ((res = mp_init (&b)) != MP_OKAY) {
    goto LBL_A;
  }

  if ((res = mp_init (&n)) != MP_OKAY) {
    goto LBL_B;
  }

  if ((res = mp_init (&x)) != MP_OKAY) {
    goto LBL_N;
  }

  if ((res = mp_init (&y)) != MP_OKAY) {
    goto LBL_X;
  }

  if ((res = mp_init (&z)) != MP_OKAY) {
    goto LBL_Y;
  }

  /* now loop making the single digit */
  while (mp_count_bits (&a) < k) {
    fprintf (stderr, "prime has %4d bits left\r", k - mp_count_bits (&a));
    fflush (stderr);
  top:
    mp_set (&b, prime_digit ());

    /* now compute z = a * b * 2 */
    if ((res = mp_mul (&a, &b, &z)) != MP_OKAY) {	/* z = a * b */
      goto LBL_Z;
    }

    if ((res = mp_copy (&z, &c)) != MP_OKAY) {	/* c = a * b */
      goto LBL_Z;
    }

    if ((res = mp_mul_2 (&z, &z)) != MP_OKAY) {	/* z = 2 * a * b */
      goto LBL_Z;
    }

    /* n = z + 1 */
    if ((res = mp_add_d (&z, 1, &n)) != MP_OKAY) {	/* n = z + 1 */
      goto LBL_Z;
    }

    /* check (n, v) == 1 */
    if ((res = mp_gcd (&n, &v, &y)) != MP_OKAY) {	/* y = (n, v) */
      goto LBL_Z;
    }

    if (mp_cmp_d (&y, 1) != MP_EQ)
      goto top;

    /* now try base x=bases[ii]  */
    for (ii = 0; ii < li; ii++) {
      mp_set (&x, bases[ii]);

      /* compute x^a mod n */
      if ((res = mp_exptmod (&x, &a, &n, &y)) != MP_OKAY) {	/* y = x^a mod n */
	goto LBL_Z;
      }

      /* if y == 1 loop */
      if (mp_cmp_d (&y, 1) == MP_EQ)
	continue;

      /* now x^2a mod n */
      if ((res = mp_sqrmod (&y, &n, &y)) != MP_OKAY) {	/* y = x^2a mod n */
	goto LBL_Z;
      }

      if (mp_cmp_d (&y, 1) == MP_EQ)
	continue;

      /* compute x^b mod n */
      if ((res = mp_exptmod (&x, &b, &n, &y)) != MP_OKAY) {	/* y = x^b mod n */
	goto LBL_Z;
      }

      /* if y == 1 loop */
      if (mp_cmp_d (&y, 1) == MP_EQ)
	continue;

      /* now x^2b mod n */
      if ((res = mp_sqrmod (&y, &n, &y)) != MP_OKAY) {	/* y = x^2b mod n */
	goto LBL_Z;
      }

      if (mp_cmp_d (&y, 1) == MP_EQ)
	continue;

      /* compute x^c mod n == x^ab mod n */
      if ((res = mp_exptmod (&x, &c, &n, &y)) != MP_OKAY) {	/* y = x^ab mod n */
	goto LBL_Z;
      }

      /* if y == 1 loop */
      if (mp_cmp_d (&y, 1) == MP_EQ)
	continue;

      /* now compute (x^c mod n)^2 */
      if ((res = mp_sqrmod (&y, &n, &y)) != MP_OKAY) {	/* y = x^2ab mod n */
	goto LBL_Z;
      }

      /* y should be 1 */
      if (mp_cmp_d (&y, 1) != MP_EQ)
	continue;
      break;
    }

    /* no bases worked? */
    if (ii == li)
      goto top;

{
   char buf[4096];

   mp_toradix(&n, buf, 10);
   printf("Certificate of primality for:\n%s\n\n", buf);
   mp_toradix(&a, buf, 10);
   printf("A == \n%s\n\n", buf);
   mp_toradix(&b, buf, 10);
   printf("B == \n%s\n\nG == %d\n", buf, bases[ii]);
   printf("----------------------------------------------------------------\n");
}

    /* a = n */
    mp_copy (&n, &a);
  }

  /* get q to be the order of the large prime subgroup */
  mp_sub_d (&n, 1, q);
  mp_div_2 (q, q);
  mp_div (q, &b, q, NULL);

  mp_exch (&n, p);

  res = MP_OKAY;
LBL_Z:mp_clear (&z);
LBL_Y:mp_clear (&y);
LBL_X:mp_clear (&x);
LBL_N:mp_clear (&n);
LBL_B:mp_clear (&b);
LBL_A:mp_clear (&a);
LBL_V:mp_clear (&v);
LBL_C:mp_clear (&c);
  return res;
}
Beispiel #15
0
bool validate_enc_signature( const wxString &sig_file_name, const wxString &key_file_name)
{
    bool ret_val = false;
    
    // Read the key_file_name, and create an instance of pub_key
    pub_key public_key;
    if( wxFileName::FileExists(key_file_name) ){
        wxTextFile key_file( key_file_name );
        if( key_file.Open() ){
            
            wxArrayString key_array;
            wxString line = key_file.GetFirstLine();
            
            while( !key_file.Eof() ){
                key_array.Add(line);
                line = key_file.GetNextLine();
            }
            
            public_key.ReadKey( key_array );
        }
    }

    if( !public_key.m_OK )
        return false;
    
    //  Validate the ENC signature file according to Spec 5.4.2.7 and 10.6.2

    //  Read the file into a string array
    if( wxFileName::FileExists(sig_file_name) ){
        wxTextFile sig_file( sig_file_name );
        if( sig_file.Open() ){
            
            wxArrayString sig_array;
            wxString line = sig_file.GetFirstLine();
            
            while( !sig_file.Eof() ){
                sig_array.Add(line);
                line = sig_file.GetNextLine();
            }

            
            // Remove the first two (R/S) lines, the Data Server Signature
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
                
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
                
            // Remove and save the next two R/S signature lines 
            wxArrayString sig_save_array;
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
                    sig_save_array.Add(line);
                    sig_save_array.Add(sig_array[i+1]);
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
                    sig_save_array.Add(line);
                    sig_save_array.Add(sig_array[i+1]);
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            //  Make one long string of the remainder of the file, to treat as a blob
            wxString pub_key_blob;
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                pub_key_blob += line;
                pub_key_blob += _T("\r\n");
            }                
            
            wxCharBuffer blob_buf = pub_key_blob.ToUTF8();

            //  Hash the blob
            SHA1Context sha1;
            uint8_t sha1sum[SHA1HashSize];
            SHA1Reset(&sha1);
            
            SHA1Input(&sha1, (uint8_t *)blob_buf.data(), strlen( blob_buf.data()) );
            SHA1Result(&sha1, sha1sum);
            
            mp_int hash, r, s;
            mp_init(&hash);
            mp_init( &r );
            mp_init( &s );
            mp_read_unsigned_bin(&hash, sha1sum, sizeof(sha1sum));
            
            
            //  Prepare the signature
            for(unsigned int i=0 ; i < sig_save_array.Count() ; i++){
                wxString line = sig_save_array[i];
                if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
                    if( (i+1) < sig_save_array.Count() ){
                        wxString sig_line = sig_save_array[i+1];
                        sig_line.Replace(_T(" "), _T("") );
                        wxCharBuffer lbuf = sig_line.ToUTF8();
                        mp_read_radix(&r, lbuf.data(), 16);
                    }
                }
                
                else if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
                    if( (i+1) < sig_save_array.Count() ){
                        wxString sig_line = sig_save_array[i+1];
                        sig_line.Replace(_T(" "), _T("") );
                        wxCharBuffer lbuf = sig_line.ToUTF8();
                        mp_read_radix(&s, lbuf.data(), 16);
                    }
                }
            }
                
            //  Verify the blob
            int val = _dsa_verify_hash(&r, &s, &hash, &(public_key.m_g), &(public_key.m_p), &(public_key.m_q), &(public_key.m_y) );            
            ret_val = (val == 1);
            
        }
    }
    
    return ret_val;
}
Beispiel #16
0
SECStatus
RSA_PrivateKeyCheck(const RSAPrivateKey *key)
{
    mp_int p, q, n, psub1, qsub1, e, d, d_p, d_q, qInv, res;
    mp_err   err = MP_OKAY;
    SECStatus rv = SECSuccess;
    MP_DIGITS(&p)    = 0;
    MP_DIGITS(&q)    = 0;
    MP_DIGITS(&n)    = 0;
    MP_DIGITS(&psub1)= 0;
    MP_DIGITS(&qsub1)= 0;
    MP_DIGITS(&e)    = 0;
    MP_DIGITS(&d)    = 0;
    MP_DIGITS(&d_p)  = 0;
    MP_DIGITS(&d_q)  = 0;
    MP_DIGITS(&qInv) = 0;
    MP_DIGITS(&res)  = 0;
    CHECK_MPI_OK( mp_init(&p)    );
    CHECK_MPI_OK( mp_init(&q)    );
    CHECK_MPI_OK( mp_init(&n)    );
    CHECK_MPI_OK( mp_init(&psub1));
    CHECK_MPI_OK( mp_init(&qsub1));
    CHECK_MPI_OK( mp_init(&e)    );
    CHECK_MPI_OK( mp_init(&d)    );
    CHECK_MPI_OK( mp_init(&d_p)  );
    CHECK_MPI_OK( mp_init(&d_q)  );
    CHECK_MPI_OK( mp_init(&qInv) );
    CHECK_MPI_OK( mp_init(&res)  );

    if (!key->modulus.data || !key->prime1.data || !key->prime2.data ||
        !key->publicExponent.data || !key->privateExponent.data ||
        !key->exponent1.data || !key->exponent2.data ||
        !key->coefficient.data) {
        /*call RSA_PopulatePrivateKey first, if the application wishes to
         * recover these parameters */
        err = MP_BADARG;
        goto cleanup;
    }

    SECITEM_TO_MPINT(key->modulus,         &n);
    SECITEM_TO_MPINT(key->prime1,          &p);
    SECITEM_TO_MPINT(key->prime2,          &q);
    SECITEM_TO_MPINT(key->publicExponent,  &e);
    SECITEM_TO_MPINT(key->privateExponent, &d);
    SECITEM_TO_MPINT(key->exponent1,       &d_p);
    SECITEM_TO_MPINT(key->exponent2,       &d_q);
    SECITEM_TO_MPINT(key->coefficient,     &qInv);
    /* p > q */
    if (mp_cmp(&p, &q) <= 0) {
	rv = SECFailure;
	goto cleanup;
    }
#define VERIFY_MPI_EQUAL(m1, m2) \
    if (mp_cmp(m1, m2) != 0) {   \
	rv = SECFailure;         \
	goto cleanup;            \
    }
#define VERIFY_MPI_EQUAL_1(m)    \
    if (mp_cmp_d(m, 1) != 0) {   \
	rv = SECFailure;         \
	goto cleanup;            \
    }
    /*
     * The following errors cannot be recovered from.
     */
    /* n == p * q */
    CHECK_MPI_OK( mp_mul(&p, &q, &res) );
    VERIFY_MPI_EQUAL(&res, &n);
    /* gcd(e, p-1) == 1 */
    CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) );
    CHECK_MPI_OK( mp_gcd(&e, &psub1, &res) );
    VERIFY_MPI_EQUAL_1(&res);
    /* gcd(e, q-1) == 1 */
    CHECK_MPI_OK( mp_sub_d(&q, 1, &qsub1) );
    CHECK_MPI_OK( mp_gcd(&e, &qsub1, &res) );
    VERIFY_MPI_EQUAL_1(&res);
    /* d*e == 1 mod p-1 */
    CHECK_MPI_OK( mp_mulmod(&d, &e, &psub1, &res) );
    VERIFY_MPI_EQUAL_1(&res);
    /* d*e == 1 mod q-1 */
    CHECK_MPI_OK( mp_mulmod(&d, &e, &qsub1, &res) );
    VERIFY_MPI_EQUAL_1(&res);
    /*
     * The following errors can be recovered from. However, the purpose of this
     * function is to check consistency, so they are not.
     */
    /* d_p == d mod p-1 */
    CHECK_MPI_OK( mp_mod(&d, &psub1, &res) );
    VERIFY_MPI_EQUAL(&res, &d_p);
    /* d_q == d mod q-1 */
    CHECK_MPI_OK( mp_mod(&d, &qsub1, &res) );
    VERIFY_MPI_EQUAL(&res, &d_q);
    /* q * q**-1 == 1 mod p */
    CHECK_MPI_OK( mp_mulmod(&q, &qInv, &p, &res) );
    VERIFY_MPI_EQUAL_1(&res);

cleanup:
    mp_clear(&n);
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&psub1);
    mp_clear(&qsub1);
    mp_clear(&e);
    mp_clear(&d);
    mp_clear(&d_p);
    mp_clear(&d_q);
    mp_clear(&qInv);
    mp_clear(&res);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    return rv;
}
Beispiel #17
0
bool validate_enc_cell( const wxString &sig_file_name, const wxString &cell_file_name)
{
    bool ret_val = false;
    
    //  Open the signature file, and extract the first R/S strings
    wxArrayString sig_array;
    wxArrayString sig_save_array;
    if( wxFileName::FileExists(sig_file_name) ){
        wxTextFile sig_file( sig_file_name );
        if( sig_file.Open() ){
            
            wxString line = sig_file.GetFirstLine();
            
            while( !sig_file.Eof() ){
                sig_array.Add(line);
                line = sig_file.GetNextLine();
            }
            
            // Remove and save the first two R/S signature lines 
             for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
                    sig_save_array.Add(line);
                    sig_save_array.Add(sig_array[i+1]);
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
                    sig_save_array.Add(line);
                    sig_save_array.Add(sig_array[i+1]);
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            // Remove the next two (R/S) lines, the Data Server Signature
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            for(unsigned int i=0 ; i < sig_array.Count() ; i++){
                wxString line = sig_array[i];
                
                if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
                    sig_array.RemoveAt(i, 2);
                    break;
                }
            }                
            
            //  Make a public key from the leftover part of the line array
        }   // File Open
    }
            
    pub_key public_key;
    public_key.ReadKey( sig_array );

    if( !public_key.m_OK )
        return false;

    //  Hash the ENC
    SHA1Context sha1;
    uint8_t sha1sum[SHA1HashSize];
    SHA1Reset(&sha1);
    
#define S63BUFSIZ 512 * 1024    
    wxFileInputStream fin( cell_file_name );
    if( fin.IsOk() ) {
        unsigned char buf[S63BUFSIZ];
        for(;;){
            if( fin.Eof())
                break;
            fin.Read(buf, S63BUFSIZ);
            size_t n_read = fin.LastRead();
 
            SHA1Input(&sha1, (uint8_t *)buf, n_read );
        }
    }
        
    SHA1Result(&sha1, sha1sum);
        

    mp_int hash, r, s;
    mp_init(&hash);
    mp_init( &r );
    mp_init( &s );
    mp_read_unsigned_bin(&hash, sha1sum, sizeof(sha1sum));

    //  Prepare the signature
    for(unsigned int i=0 ; i < sig_save_array.Count() ; i++){
        wxString line = sig_save_array[i];
        if( line.Upper().Find(_T("PART R")) != wxNOT_FOUND ){
            if( (i+1) < sig_save_array.Count() ){
                wxString sig_line = sig_save_array[i+1];
                sig_line.Replace(_T(" "), _T("") );
        wxCharBuffer lbuf = sig_line.ToUTF8();
        mp_read_radix(&r, lbuf.data(), 16);
            }
        }
        
        else if( line.Upper().Find(_T("PART S")) != wxNOT_FOUND ){
            if( (i+1) < sig_save_array.Count() ){
                wxString sig_line = sig_save_array[i+1];
                sig_line.Replace(_T(" "), _T("") );
        wxCharBuffer lbuf = sig_line.ToUTF8();
        mp_read_radix(&s, lbuf.data(), 16);
            }
        }
    }
    
    //  Verify the blob
    int val = _dsa_verify_hash(&r, &s, &hash, &(public_key.m_g), &(public_key.m_p), &(public_key.m_q), &(public_key.m_y) );            
    ret_val = (val == 1);
    
    return ret_val;   
}
Beispiel #18
0
/*
** Generate and return a new RSA public and private key.
**	Both keys are encoded in a single RSAPrivateKey structure.
**	"cx" is the random number generator context
**	"keySizeInBits" is the size of the key to be generated, in bits.
**	   512, 1024, etc.
**	"publicExponent" when not NULL is a pointer to some data that
**	   represents the public exponent to use. The data is a byte
**	   encoded integer, in "big endian" order.
*/
RSAPrivateKey *
RSA_NewKey(int keySizeInBits, SECItem *publicExponent)
{
    unsigned int primeLen;
    mp_int p, q, e, d;
    int kiter;
    mp_err   err = MP_OKAY;
    SECStatus rv = SECSuccess;
    int prerr = 0;
    RSAPrivateKey *key = NULL;
    PLArenaPool *arena = NULL;
    /* Require key size to be a multiple of 16 bits. */
    if (!publicExponent || keySizeInBits % 16 != 0 ||
	    BAD_RSA_KEY_SIZE(keySizeInBits/8, publicExponent->len)) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return NULL;
    }
    /* 1. Allocate arena & key */
    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    if (!arena) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return NULL;
    }
    key = PORT_ArenaZNew(arena, RSAPrivateKey);
    if (!key) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	PORT_FreeArena(arena, PR_TRUE);
	return NULL;
    }
    key->arena = arena;
    /* length of primes p and q (in bytes) */
    primeLen = keySizeInBits / (2 * PR_BITS_PER_BYTE);
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&q) = 0;
    MP_DIGITS(&e) = 0;
    MP_DIGITS(&d) = 0;
    CHECK_MPI_OK( mp_init(&p) );
    CHECK_MPI_OK( mp_init(&q) );
    CHECK_MPI_OK( mp_init(&e) );
    CHECK_MPI_OK( mp_init(&d) );
    /* 2.  Set the version number (PKCS1 v1.5 says it should be zero) */
    SECITEM_AllocItem(arena, &key->version, 1);
    key->version.data[0] = 0;
    /* 3.  Set the public exponent */
    SECITEM_TO_MPINT(*publicExponent, &e);
    kiter = 0;
    do {
	prerr = 0;
	PORT_SetError(0);
	CHECK_SEC_OK( generate_prime(&p, primeLen) );
	CHECK_SEC_OK( generate_prime(&q, primeLen) );
	/* Assure q < p */
	if (mp_cmp(&p, &q) < 0)
	    mp_exch(&p, &q);
	/* Attempt to use these primes to generate a key */
	rv = rsa_build_from_primes(&p, &q, 
			&e, PR_FALSE,  /* needPublicExponent=false */
			&d, PR_TRUE,   /* needPrivateExponent=true */
			key, keySizeInBits);
	if (rv == SECSuccess)
	    break; /* generated two good primes */
	prerr = PORT_GetError();
	kiter++;
	/* loop until have primes */
    } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS);
    if (prerr)
	goto cleanup;
cleanup:
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&e);
    mp_clear(&d);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    if (rv && arena) {
	PORT_FreeArena(arena, PR_TRUE);
	key = NULL;
    }
    return key;
}
Beispiel #19
0
/* Construct ECGroup from hex parameters and name, if any. Called by
 * ECGroup_fromHex and ECGroup_fromName. */
ECGroup *
ecgroup_fromNameAndHex(const ECCurveName name,
                       const ECCurveParams * params)
{
    mp_int irr, curvea, curveb, genx, geny, order;
    int bits;
    ECGroup *group = NULL;
    mp_err res = MP_OKAY;

    /* initialize values */
    MP_DIGITS(&irr) = 0;
    MP_DIGITS(&curvea) = 0;
    MP_DIGITS(&curveb) = 0;
    MP_DIGITS(&genx) = 0;
    MP_DIGITS(&geny) = 0;
    MP_DIGITS(&order) = 0;
    MP_CHECKOK(mp_init(&irr));
    MP_CHECKOK(mp_init(&curvea));
    MP_CHECKOK(mp_init(&curveb));
    MP_CHECKOK(mp_init(&genx));
    MP_CHECKOK(mp_init(&geny));
    MP_CHECKOK(mp_init(&order));
    MP_CHECKOK(mp_read_radix(&irr, params->irr, 16));
    MP_CHECKOK(mp_read_radix(&curvea, params->curvea, 16));
    MP_CHECKOK(mp_read_radix(&curveb, params->curveb, 16));
    MP_CHECKOK(mp_read_radix(&genx, params->genx, 16));
    MP_CHECKOK(mp_read_radix(&geny, params->geny, 16));
    MP_CHECKOK(mp_read_radix(&order, params->order, 16));

    /* determine number of bits */
    bits = mpl_significant_bits(&irr) - 1;
    if (bits < MP_OKAY) {
        res = bits;
        goto CLEANUP;
    }

    /* determine which optimizations (if any) to use */
    if (params->field == ECField_GFp) {
        switch (name) {
#ifdef NSS_ECC_MORE_THAN_SUITE_B
#ifdef ECL_USE_FP
        case ECCurve_SECG_PRIME_160R1:
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_secp160r1_fp(group));
            break;
#endif
        case ECCurve_SECG_PRIME_192R1:
#ifdef ECL_USE_FP
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_nistp192_fp(group));
#else
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_gfp192(group, name));
#endif
            break;
        case ECCurve_SECG_PRIME_224R1:
#ifdef ECL_USE_FP
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_nistp224_fp(group));
#else
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_gfp224(group, name));
#endif
            break;
#endif /* NSS_ECC_MORE_THAN_SUITE_B */
        case ECCurve_SECG_PRIME_256R1:
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_gfp256(group, name));
            MP_CHECKOK(ec_group_set_gfp256_32(group, name));
            break;
        case ECCurve_SECG_PRIME_521R1:
            group =
                ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny,
                                &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
            MP_CHECKOK(ec_group_set_gfp521(group, name));
            break;
        default:
            /* use generic arithmetic */
            group =
                ECGroup_consGFp_mont(&irr, &curvea, &curveb, &genx, &geny,
                                     &order, params->cofactor);
            if (group == NULL) {
                res = MP_UNDEF;
                goto CLEANUP;
            }
        }
#ifdef NSS_ECC_MORE_THAN_SUITE_B
    } else if (params->field == ECField_GF2m) {
        group = ECGroup_consGF2m(&irr, NULL, &curvea, &curveb, &genx, &geny, &order, params->cofactor);
        if (group == NULL) {
            res = MP_UNDEF;
            goto CLEANUP;
        }
        if ((name == ECCurve_NIST_K163) ||
                (name == ECCurve_NIST_B163) ||
                (name == ECCurve_SECG_CHAR2_163R1)) {
            MP_CHECKOK(ec_group_set_gf2m163(group, name));
        } else if ((name == ECCurve_SECG_CHAR2_193R1) ||
                   (name == ECCurve_SECG_CHAR2_193R2)) {
            MP_CHECKOK(ec_group_set_gf2m193(group, name));
        } else if ((name == ECCurve_NIST_K233) ||
                   (name == ECCurve_NIST_B233)) {
            MP_CHECKOK(ec_group_set_gf2m233(group, name));
        }
#endif
    } else {
        res = MP_UNDEF;
        goto CLEANUP;
    }

    /* set name, if any */
    if ((group != NULL) && (params->text != NULL)) {
        group->text = strdup(params->text);
        if (group->text == NULL) {
            res = MP_MEM;
        }
    }

CLEANUP:
    mp_clear(&irr);
    mp_clear(&curvea);
    mp_clear(&curveb);
    mp_clear(&genx);
    mp_clear(&geny);
    mp_clear(&order);
    if (res != MP_OKAY) {
        ECGroup_free(group);
        return NULL;
    }
    return group;
}
Beispiel #20
0
/*
 * Try to find the two primes based on 2 exponents plus either a prime
 *   or a modulus.
 *
 * In: e, d and either p or n (depending on the setting of hasModulus).
 * Out: p,q.
 * 
 * Step 1, Since d = e**-1 mod phi, we know that d*e == 1 mod phi, or
 *	d*e = 1+k*phi, or d*e-1 = k*phi. since d is less than phi and e is
 *	usually less than d, then k must be an integer between e-1 and 1 
 *	(probably on the order of e).
 * Step 1a, If we were passed just a prime, we can divide k*phi by that
 *      prime-1 and get k*(q-1). This will reduce the size of our division
 *      through the rest of the loop.
 * Step 2, Loop through the values k=e-1 to 1 looking for k. k should be on
 *	the order or e, and e is typically small. This may take a while for
 *	a large random e. We are looking for a k that divides kphi
 *	evenly. Once we find a k that divides kphi evenly, we assume it 
 *	is the true k. It's possible this k is not the 'true' k but has 
 *	swapped factors of p-1 and/or q-1. Because of this, we 
 *	tentatively continue Steps 3-6 inside this loop, and may return looking
 *	for another k on failure.
 * Step 3, Calculate are tentative phi=kphi/k. Note: real phi is (p-1)*(q-1).
 * Step 4a, if we have a prime, kphi is already k*(q-1), so phi is or tenative
 *      q-1. q = phi+1. If k is correct, q should be the right length and 
 *      prime.
 * Step 4b, It's possible q-1 and k could have swapped factors. We now have a
 * 	possible solution that meets our criteria. It may not be the only 
 *      solution, however, so we keep looking. If we find more than one, 
 *      we will fail since we cannot determine which is the correct
 *      solution, and returning the wrong modulus will compromise both
 *      moduli. If no other solution is found, we return the unique solution.
 * Step 5a, If we have the modulus (n=pq), then use the following formula to 
 * 	calculate  s=(p+q): , phi = (p-1)(q-1) = pq  -p-q +1 = n-s+1. so
 *	s=n-phi+1.
 * Step 5b, Use n=pq and s=p+q to solve for p and q as follows:
 *	since q=s-p, then n=p*(s-p)= sp - p^2, rearranging p^2-s*p+n = 0.
 *	from the quadratic equation we have p=1/2*(s+sqrt(s*s-4*n)) and
 *	q=1/2*(s-sqrt(s*s-4*n)) if s*s-4*n is a perfect square, we are DONE.
 *	If it is not, continue in our look looking for another k. NOTE: the
 *	code actually distributes the 1/2 and results in the equations:
 *	sqrt = sqrt(s/2*s/2-n), p=s/2+sqrt, q=s/2-sqrt. The algebra saves us
 *	and extra divide by 2 and a multiply by 4.
 * 
 * This will return p & q. q may be larger than p in the case that p was given
 * and it was the smaller prime.
 */
static mp_err
rsa_get_primes_from_exponents(mp_int *e, mp_int *d, mp_int *p, mp_int *q,
			      mp_int *n, PRBool hasModulus, 
			      unsigned int keySizeInBits)
{
    mp_int kphi; /* k*phi */
    mp_int k;    /* current guess at 'k' */
    mp_int phi;  /* (p-1)(q-1) */
    mp_int s;    /* p+q/2 (s/2 in the algebra) */
    mp_int r;    /* remainder */
    mp_int tmp; /* p-1 if p is given, n+1 is modulus is given */
    mp_int sqrt; /* sqrt(s/2*s/2-n) */
    mp_err err = MP_OKAY;
    unsigned int order_k;

    MP_DIGITS(&kphi) = 0;
    MP_DIGITS(&phi) = 0;
    MP_DIGITS(&s) = 0;
    MP_DIGITS(&k) = 0;
    MP_DIGITS(&r) = 0;
    MP_DIGITS(&tmp) = 0;
    MP_DIGITS(&sqrt) = 0;
    CHECK_MPI_OK( mp_init(&kphi) );
    CHECK_MPI_OK( mp_init(&phi) );
    CHECK_MPI_OK( mp_init(&s) );
    CHECK_MPI_OK( mp_init(&k) );
    CHECK_MPI_OK( mp_init(&r) );
    CHECK_MPI_OK( mp_init(&tmp) );
    CHECK_MPI_OK( mp_init(&sqrt) );

    /* our algorithm looks for a factor k whose maximum size is dependent
     * on the size of our smallest exponent, which had better be the public
     * exponent (if it's the private, the key is vulnerable to a brute force
     * attack).
     * 
     * since our factor search is linear, we need to limit the maximum
     * size of the public key. this should not be a problem normally, since 
     * public keys are usually small. 
     *
     * if we want to handle larger public key sizes, we should have
     * a version which tries to 'completely' factor k*phi (where completely
     * means 'factor into primes, or composites with which are products of
     * large primes). Once we have all the factors, we can sort them out and
     * try different combinations to form our phi. The risk is if (p-1)/2,
     * (q-1)/2, and k are all large primes. In any case if the public key
     * is small (order of 20 some bits), then a linear search for k is 
     * manageable.
     */
    if (mpl_significant_bits(e) > 23) {
	err=MP_RANGE;
	goto cleanup;
    }

    /* calculate k*phi = e*d - 1 */
    CHECK_MPI_OK( mp_mul(e, d, &kphi) );
    CHECK_MPI_OK( mp_sub_d(&kphi, 1, &kphi) );


    /* kphi is (e*d)-1, which is the same as k*(p-1)(q-1)
     * d < (p-1)(q-1), therefor k must be less than e-1
     * We can narrow down k even more, though. Since p and q are odd and both 
     * have their high bit set, then we know that phi must be on order of 
     * keySizeBits.
     */
    order_k = (unsigned)mpl_significant_bits(&kphi) - keySizeInBits;

    /* for (k=kinit; order(k) >= order_k; k--) { */
    /* k=kinit: k can't be bigger than  kphi/2^(keySizeInBits -1) */
    CHECK_MPI_OK( mp_2expt(&k,keySizeInBits-1) );
    CHECK_MPI_OK( mp_div(&kphi, &k, &k, NULL));
    if (mp_cmp(&k,e) >= 0) {
	/* also can't be bigger then e-1 */
        CHECK_MPI_OK( mp_sub_d(e, 1, &k) );
    }

    /* calculate our temp value */
    /* This saves recalculating this value when the k guess is wrong, which
     * is reasonably frequent. */
    /* for the modulus case, tmp = n+1 (used to calculate p+q = tmp - phi) */
    /* for the prime case, tmp = p-1 (used to calculate q-1= phi/tmp) */
    if (hasModulus) {
	CHECK_MPI_OK( mp_add_d(n, 1, &tmp) );
    } else {
	CHECK_MPI_OK( mp_sub_d(p, 1, &tmp) );
	CHECK_MPI_OK(mp_div(&kphi,&tmp,&kphi,&r));
	if (mp_cmp_z(&r) != 0) {
	    /* p-1 doesn't divide kphi, some parameter wasn't correct */
	    err=MP_RANGE;
	    goto cleanup;
	}
	mp_zero(q);
	/* kphi is now k*(q-1) */
    }

    /* rest of the for loop */
    for (; (err == MP_OKAY) && (mpl_significant_bits(&k) >= order_k); 
						err = mp_sub_d(&k, 1, &k)) {
	/* looking for k as a factor of kphi */
	CHECK_MPI_OK(mp_div(&kphi,&k,&phi,&r));
	if (mp_cmp_z(&r) != 0) {
	    /* not a factor, try the next one */
	    continue;
	}
	/* we have a possible phi, see if it works */
	if (!hasModulus) {
	    if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits/2) {
		/* phi is not the right size */
		continue;
	    }
	    /* phi should be divisible by 2, since
	     * q is odd and phi=(q-1). */
	    if (mpp_divis_d(&phi,2) == MP_NO) {
		/* phi is not divisible by 4 */
		continue;
	    }
	    /* we now have a candidate for the second prime */
	    CHECK_MPI_OK(mp_add_d(&phi, 1, &tmp));
	    
	    /* check to make sure it is prime */
	    err = rsa_is_prime(&tmp);
	    if (err != MP_OKAY) {
		if (err == MP_NO) {
		    /* No, then we still have the wrong phi */
		    err = MP_OKAY;
        	    continue;
		}
		goto cleanup;
	    }
	    /*
	     * It is possible that we have the wrong phi if 
	     * k_guess*(q_guess-1) = k*(q-1) (k and q-1 have swapped factors).
	     * since our q_quess is prime, however. We have found a valid
	     * rsa key because:
	     *   q is the correct order of magnitude.
	     *   phi = (p-1)(q-1) where p and q are both primes.
	     *   e*d mod phi = 1.
	     * There is no way to know from the info given if this is the 
	     * original key. We never want to return the wrong key because if
	     * two moduli with the same factor is known, then euclid's gcd
	     * algorithm can be used to find that factor. Even though the 
	     * caller didn't pass the original modulus, it doesn't mean the
	     * modulus wasn't known or isn't available somewhere. So to be safe
	     * if we can't be sure we have the right q, we don't return any.
	     * 
	     * So to make sure we continue looking for other valid q's. If none
	     * are found, then we can safely return this one, otherwise we just
	     * fail */
	    if (mp_cmp_z(q) != 0) {
		/* this is the second valid q, don't return either, 
		 * just fail */
		err = MP_RANGE;
		break;
	    }
	    /* we only have one q so far, save it and if no others are found,
	     * it's safe to return it */
	    CHECK_MPI_OK(mp_copy(&tmp, q));
	    continue;
	}
	/* test our tentative phi */
	/* phi should be the correct order */
	if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits) {
	    /* phi is not the right size */
	    continue;
	}
	/* phi should be divisible by 4, since
	 * p and q are odd and phi=(p-1)(q-1). */
	if (mpp_divis_d(&phi,4) == MP_NO) {
	    /* phi is not divisible by 4 */
	    continue;
	}
	/* n was given, calculate s/2=(p+q)/2 */
	CHECK_MPI_OK( mp_sub(&tmp, &phi, &s) );
	CHECK_MPI_OK( mp_div_2(&s, &s) );

	/* calculate sqrt(s/2*s/2-n) */
	CHECK_MPI_OK(mp_sqr(&s,&sqrt));
	CHECK_MPI_OK(mp_sub(&sqrt,n,&r));  /* r as a tmp */
	CHECK_MPI_OK(mp_sqrt(&r,&sqrt));
	/* make sure it's a perfect square */
	/* r is our original value we took the square root of */
	/* q is the square of our tentative square root. They should be equal*/
	CHECK_MPI_OK(mp_sqr(&sqrt,q)); /* q as a tmp */
	if (mp_cmp(&r,q) != 0) {
	    /* sigh according to the doc, mp_sqrt could return sqrt-1 */
	   CHECK_MPI_OK(mp_add_d(&sqrt,1,&sqrt));
	   CHECK_MPI_OK(mp_sqr(&sqrt,q));
	   if (mp_cmp(&r,q) != 0) {
		/* s*s-n not a perfect square, this phi isn't valid, find 			 * another.*/
		continue;
	    }
	}

	/* NOTE: In this case we know we have the one and only answer.
	 * "Why?", you ask. Because:
	 *    1) n is a composite of two large primes (or it wasn't a
	 *       valid RSA modulus).
	 *    2) If we know any number such that x^2-n is a perfect square 
	 *       and x is not (n+1)/2, then we can calculate 2 non-trivial
	 *       factors of n.
	 *    3) Since we know that n has only 2 non-trivial prime factors, 
	 *       we know the two factors we have are the only possible factors.
	 */

	/* Now we are home free to calculate p and q */
	/* p = s/2 + sqrt, q= s/2 - sqrt */
	CHECK_MPI_OK(mp_add(&s,&sqrt,p));
	CHECK_MPI_OK(mp_sub(&s,&sqrt,q));
	break;
    }
    if ((unsigned)mpl_significant_bits(&k) < order_k) {
	if (hasModulus || (mp_cmp_z(q) == 0)) {
	    /* If we get here, something was wrong with the parameters we 
	     * were given */
	    err = MP_RANGE; 
	}
    }
cleanup:
    mp_clear(&kphi);
    mp_clear(&phi);
    mp_clear(&s);
    mp_clear(&k);
    mp_clear(&r);
    mp_clear(&tmp);
    mp_clear(&sqrt);
    return err;
}
Beispiel #21
0
SECStatus 
DH_NewKey(DHParams *params, DHPrivateKey **privKey)
{
    PLArenaPool *arena;
    DHPrivateKey *key;
    mp_int g, xa, p, Ya;
    mp_err   err = MP_OKAY;
    SECStatus rv = SECSuccess;
    if (!params || !privKey) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    if (!arena) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return SECFailure;
    }
    key = (DHPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DHPrivateKey));
    if (!key) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	PORT_FreeArena(arena, PR_TRUE);
	return SECFailure;
    }
    key->arena = arena;
    MP_DIGITS(&g)  = 0;
    MP_DIGITS(&xa) = 0;
    MP_DIGITS(&p)  = 0;
    MP_DIGITS(&Ya) = 0;
    CHECK_MPI_OK( mp_init(&g)  );
    CHECK_MPI_OK( mp_init(&xa) );
    CHECK_MPI_OK( mp_init(&p)  );
    CHECK_MPI_OK( mp_init(&Ya) );
    /* Set private key's p */
    CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->prime, &params->prime) );
    SECITEM_TO_MPINT(key->prime, &p);
    /* Set private key's g */
    CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->base, &params->base) );
    SECITEM_TO_MPINT(key->base, &g);
    /* Generate private key xa */
    SECITEM_AllocItem(arena, &key->privateValue,
                      dh_GetSecretKeyLen(params->prime.len));
    CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(key->privateValue.data, 
                                  key->privateValue.len));
    SECITEM_TO_MPINT( key->privateValue, &xa );
    /* xa < p */
    CHECK_MPI_OK( mp_mod(&xa, &p, &xa) );
    /* Compute public key Ya = g ** xa mod p */
    CHECK_MPI_OK( mp_exptmod(&g, &xa, &p, &Ya) );
    MPINT_TO_SECITEM(&Ya, &key->publicValue, key->arena);
    *privKey = key;
cleanup:
    mp_clear(&g);
    mp_clear(&xa);
    mp_clear(&p);
    mp_clear(&Ya);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    if (rv) {
	*privKey = NULL;
	PORT_FreeArena(arena, PR_TRUE);
    }
    return rv;
}
Beispiel #22
0
/*
 * take a private key with only a few elements and fill out the missing pieces.
 *
 * All the entries will be overwritten with data allocated out of the arena
 * If no arena is supplied, one will be created.
 *
 * The following fields must be supplied in order for this function
 * to succeed:
 *   one of either publicExponent or privateExponent
 *   two more of the following 5 parameters.
 *      modulus (n)
 *      prime1  (p)
 *      prime2  (q)
 *      publicExponent (e)
 *      privateExponent (d)
 *
 * NOTE: if only the publicExponent, privateExponent, and one prime is given,
 * then there may be more than one RSA key that matches that combination.
 *
 * All parameters will be replaced in the key structure with new parameters
 * Allocated out of the arena. There is no attempt to free the old structures.
 * Prime1 will always be greater than prime2 (even if the caller supplies the
 * smaller prime as prime1 or the larger prime as prime2). The parameters are
 * not overwritten on failure.
 *
 *  How it works:
 *     We can generate all the parameters from:
 *        one of the exponents, plus the two primes. (rsa_build_key_from_primes) *
 *     If we are given one of the exponents and both primes, we are done.
 *     If we are given one of the exponents, the modulus and one prime, we 
 *        caclulate the second prime by dividing the modulus by the given 
 *        prime, giving us and exponent and 2 primes.
 *     If we are given 2 exponents and either the modulus or one of the primes
 *        we calculate k*phi = d*e-1, where k is an integer less than d which 
 *        divides d*e-1. We find factor k so we can isolate phi.
 *            phi = (p-1)(q-1)
 *       If one of the primes are given, we can use phi to find the other prime
 *        as follows: q = (phi/(p-1)) + 1. We now have 2 primes and an 
 *        exponent. (NOTE: if more then one prime meets this condition, the
 *        operation will fail. See comments elsewhere in this file about this).
 *       If the modulus is given, then we can calculate the sum of the primes
 *        as follows: s := (p+q), phi = (p-1)(q-1) = pq -p - q +1, pq = n ->
 *        phi = n - s + 1, s = n - phi +1.  Now that we have s = p+q and n=pq,
 *	  we can solve our 2 equations and 2 unknowns as follows: q=s-p ->
 *        n=p*(s-p)= sp -p^2 -> p^2-sp+n = 0. Using the quadratic to solve for
 *        p, p=1/2*(s+ sqrt(s*s-4*n)) [q=1/2*(s-sqrt(s*s-4*n)]. We again have
 *        2 primes and an exponent.
 *
 */
SECStatus
RSA_PopulatePrivateKey(RSAPrivateKey *key)
{
    PLArenaPool *arena = NULL;
    PRBool needPublicExponent = PR_TRUE;
    PRBool needPrivateExponent = PR_TRUE;
    PRBool hasModulus = PR_FALSE;
    unsigned int keySizeInBits = 0;
    int prime_count = 0;
    /* standard RSA nominclature */
    mp_int p, q, e, d, n;
    /* remainder */
    mp_int r;
    mp_err err = 0;
    SECStatus rv = SECFailure;

    MP_DIGITS(&p) = 0;
    MP_DIGITS(&q) = 0;
    MP_DIGITS(&e) = 0;
    MP_DIGITS(&d) = 0;
    MP_DIGITS(&n) = 0;
    MP_DIGITS(&r) = 0;
    CHECK_MPI_OK( mp_init(&p) );
    CHECK_MPI_OK( mp_init(&q) );
    CHECK_MPI_OK( mp_init(&e) );
    CHECK_MPI_OK( mp_init(&d) );
    CHECK_MPI_OK( mp_init(&n) );
    CHECK_MPI_OK( mp_init(&r) );
 
    /* if the key didn't already have an arena, create one. */
    if (key->arena == NULL) {
	arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
	if (!arena) {
	    goto cleanup;
	}
	key->arena = arena;
    }

    /* load up the known exponents */
    if (key->publicExponent.data) {
        SECITEM_TO_MPINT(key->publicExponent, &e);
	needPublicExponent = PR_FALSE;
    } 
    if (key->privateExponent.data) {
        SECITEM_TO_MPINT(key->privateExponent, &d);
	needPrivateExponent = PR_FALSE;
    }
    if (needPrivateExponent && needPublicExponent) {
	/* Not enough information, we need at least one exponent */
	err = MP_BADARG;
	goto cleanup;
    }

    /* load up the known primes. If only one prime is given, it will be
     * assigned 'p'. Once we have both primes, well make sure p is the larger.
     * The value prime_count tells us howe many we have acquired.
     */
    if (key->prime1.data) {
	int primeLen = key->prime1.len;
	if (key->prime1.data[0] == 0) {
	   primeLen--;
	}
	keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
        SECITEM_TO_MPINT(key->prime1, &p);
	prime_count++;
    }
    if (key->prime2.data) {
	int primeLen = key->prime2.len;
	if (key->prime2.data[0] == 0) {
	   primeLen--;
	}
	keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
        SECITEM_TO_MPINT(key->prime2, prime_count ? &q : &p);
	prime_count++;
    }
    /* load up the modulus */
    if (key->modulus.data) {
	int modLen = key->modulus.len;
	if (key->modulus.data[0] == 0) {
	   modLen--;
	}
	keySizeInBits = modLen * PR_BITS_PER_BYTE;
	SECITEM_TO_MPINT(key->modulus, &n);
	hasModulus = PR_TRUE;
    }
    /* if we have the modulus and one prime, calculate the second. */
    if ((prime_count == 1) && (hasModulus)) {
	mp_div(&n,&p,&q,&r);
	if (mp_cmp_z(&r) != 0) {
	   /* p is not a factor or n, fail */
	   err = MP_BADARG;
	   goto cleanup;
	}
	prime_count++;
    }

    /* If we didn't have enough primes try to calculate the primes from
     * the exponents */
    if (prime_count < 2) {
	/* if we don't have at least 2 primes at this point, then we need both
	 * exponents and one prime or a modulus*/
	if (!needPublicExponent && !needPrivateExponent &&
		((prime_count > 0) || hasModulus)) {
	    CHECK_MPI_OK(rsa_get_primes_from_exponents(&e,&d,&p,&q,
			&n,hasModulus,keySizeInBits));
	} else {
	    /* not enough given parameters to get both primes */
	    err = MP_BADARG;
	    goto cleanup;
	}
     }

     /* force p to the the larger prime */
     if (mp_cmp(&p, &q) < 0)
	mp_exch(&p, &q);

     /* we now have our 2 primes and at least one exponent, we can fill
      * in the key */
     rv = rsa_build_from_primes(&p, &q, 
			&e, needPublicExponent,
			&d, needPrivateExponent,
			key, keySizeInBits);
cleanup:
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&e);
    mp_clear(&d);
    mp_clear(&n);
    mp_clear(&r);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    if (rv && arena) {
	PORT_FreeArena(arena, PR_TRUE);
	key->arena = NULL;
    }
    return rv;
}
Beispiel #23
0
SECStatus 
KEA_Derive(SECItem *prime, 
           SECItem *public1, 
           SECItem *public2, 
           SECItem *private1, 
           SECItem *private2,
           SECItem *derivedSecret)
{
    mp_int p, Y, R, r, x, t, u, w;
    mp_err err;
    unsigned char *secret = NULL;
    unsigned int len = 0, offset;
    if (!prime || !public1 || !public2 || !private1 || !private2 ||
        !derivedSecret) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    memset(derivedSecret, 0, sizeof *derivedSecret);
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&Y) = 0;
    MP_DIGITS(&R) = 0;
    MP_DIGITS(&r) = 0;
    MP_DIGITS(&x) = 0;
    MP_DIGITS(&t) = 0;
    MP_DIGITS(&u) = 0;
    MP_DIGITS(&w) = 0;
    CHECK_MPI_OK( mp_init(&p) );
    CHECK_MPI_OK( mp_init(&Y) );
    CHECK_MPI_OK( mp_init(&R) );
    CHECK_MPI_OK( mp_init(&r) );
    CHECK_MPI_OK( mp_init(&x) );
    CHECK_MPI_OK( mp_init(&t) );
    CHECK_MPI_OK( mp_init(&u) );
    CHECK_MPI_OK( mp_init(&w) );
    SECITEM_TO_MPINT(*prime,    &p);
    SECITEM_TO_MPINT(*public1,  &Y);
    SECITEM_TO_MPINT(*public2,  &R);
    SECITEM_TO_MPINT(*private1, &r);
    SECITEM_TO_MPINT(*private2, &x);
    /* t = DH(Y, r, p) = Y ** r mod p */
    CHECK_MPI_OK( mp_exptmod(&Y, &r, &p, &t) );
    /* u = DH(R, x, p) = R ** x mod p */
    CHECK_MPI_OK( mp_exptmod(&R, &x, &p, &u) );
    /* w = (t + u) mod p */
    CHECK_MPI_OK( mp_addmod(&t, &u, &p, &w) );
    /* allocate a buffer for the full derived secret */
    len = mp_unsigned_octet_size(&w);
    secret = PORT_Alloc(len);
    if (secret == NULL) {
	err = MP_MEM;
	goto cleanup;
    }
    /* grab the secret */
    err = mp_to_unsigned_octets(&w, secret, len);
    if (err > 0) err = MP_OKAY;
    /* allocate output buffer */
    if (SECITEM_AllocItem(NULL, derivedSecret, KEA_DERIVED_SECRET_LEN)
								  == NULL) {
	err = MP_MEM;
	goto cleanup;
    }
    memset(derivedSecret->data, 0, derivedSecret->len);
    /* copy in the 128 lsb of the secret */
    if (len >= KEA_DERIVED_SECRET_LEN) {
	memcpy(derivedSecret->data, secret + (len - KEA_DERIVED_SECRET_LEN),
	       KEA_DERIVED_SECRET_LEN);
    } else {
	offset = KEA_DERIVED_SECRET_LEN - len;
	memcpy(derivedSecret->data + offset, secret, len);
    }
cleanup:
    mp_clear(&p);
    mp_clear(&Y);
    mp_clear(&R);
    mp_clear(&r);
    mp_clear(&x);
    mp_clear(&t);
    mp_clear(&u);
    mp_clear(&w);
    if (secret)
	PORT_ZFree(secret, len);
    if (err) {
	MP_TO_SEC_ERROR(err);
	if (derivedSecret->data) 
	    PORT_ZFree(derivedSecret->data, derivedSecret->len);
	return SECFailure;
    }
    return SECSuccess;
}
Beispiel #24
0
/*
** Perform a raw public-key operation 
**	Length of input and output buffers are equal to key's modulus len.
*/
SECStatus 
RSA_PublicKeyOp(RSAPublicKey  *key, 
                unsigned char *output, 
                const unsigned char *input)
{
    unsigned int modLen, expLen, offset;
    mp_int n, e, m, c;
    mp_err err   = MP_OKAY;
    SECStatus rv = SECSuccess;
    if (!key || !output || !input) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    MP_DIGITS(&n) = 0;
    MP_DIGITS(&e) = 0;
    MP_DIGITS(&m) = 0;
    MP_DIGITS(&c) = 0;
    CHECK_MPI_OK( mp_init(&n) );
    CHECK_MPI_OK( mp_init(&e) );
    CHECK_MPI_OK( mp_init(&m) );
    CHECK_MPI_OK( mp_init(&c) );
    modLen = rsa_modulusLen(&key->modulus);
    expLen = rsa_modulusLen(&key->publicExponent);
    /* 1.  Obtain public key (n, e) */
    if (BAD_RSA_KEY_SIZE(modLen, expLen)) {
    	PORT_SetError(SEC_ERROR_INVALID_KEY);
	rv = SECFailure;
	goto cleanup;
    }
    SECITEM_TO_MPINT(key->modulus, &n);
    SECITEM_TO_MPINT(key->publicExponent, &e);
    if (e.used > n.used) {
	/* exponent should not be greater than modulus */
    	PORT_SetError(SEC_ERROR_INVALID_KEY);
	rv = SECFailure;
	goto cleanup;
    }
    /* 2. check input out of range (needs to be in range [0..n-1]) */
    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
        PORT_SetError(SEC_ERROR_INPUT_LEN);
        rv = SECFailure;
        goto cleanup;
    }
    /* 2 bis.  Represent message as integer in range [0..n-1] */
    CHECK_MPI_OK( mp_read_unsigned_octets(&m, input, modLen) );
    /* 3.  Compute c = m**e mod n */
#ifdef USE_MPI_EXPT_D
    /* XXX see which is faster */
    if (MP_USED(&e) == 1) {
	CHECK_MPI_OK( mp_exptmod_d(&m, MP_DIGIT(&e, 0), &n, &c) );
    } else
#endif
    CHECK_MPI_OK( mp_exptmod(&m, &e, &n, &c) );
    /* 4.  result c is ciphertext */
    err = mp_to_fixlen_octets(&c, output, modLen);
    if (err >= 0) err = MP_OKAY;
cleanup:
    mp_clear(&n);
    mp_clear(&e);
    mp_clear(&m);
    mp_clear(&c);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    return rv;
}
/* finds the next prime after the number "a" using "t" trials
 * of Miller-Rabin.
 *
 * bbs_style = 1 means the prime must be congruent to 3 mod 4
 */
int mp_prime_next_prime(mp_int *a, int t, int bbs_style)
{
    int      err, res = MP_NO, x, y;
    mp_digit res_tab[PRIME_SIZE], step, kstep;
    mp_int   b;

    /* ensure t is valid */
    if (t <= 0 || t > PRIME_SIZE) {
        return MP_VAL;
    }

    /* force positive */
    a->sign = MP_ZPOS;

    /* simple algo if a is less than the largest prime in the table */
    if (mp_cmp_d(a, ltm_prime_tab[PRIME_SIZE-1]) == MP_LT) {
        /* find which prime it is bigger than */
        for (x = PRIME_SIZE - 2; x >= 0; x--) {
            if (mp_cmp_d(a, ltm_prime_tab[x]) != MP_LT) {
                if (bbs_style == 1) {
                    /* ok we found a prime smaller or
                     * equal [so the next is larger]
                     *
                     * however, the prime must be
                     * congruent to 3 mod 4
                     */
                    if ((ltm_prime_tab[x + 1] & 3) != 3) {
                        /* scan upwards for a prime congruent to 3 mod 4 */
                        for (y = x + 1; y < PRIME_SIZE; y++) {
                            if ((ltm_prime_tab[y] & 3) == 3) {
                                mp_set(a, ltm_prime_tab[y]);
                                return MP_OKAY;
                            }
                        }
                    }
                } else {
                    mp_set(a, ltm_prime_tab[x + 1]);
                    return MP_OKAY;
                }
            }
        }
        /* at this point a maybe 1 */
        if (mp_cmp_d(a, 1) == MP_EQ) {
            mp_set(a, 2);
            return MP_OKAY;
        }
        /* fall through to the sieve */
    }

    /* generate a prime congruent to 3 mod 4 or 1/3 mod 4? */
    if (bbs_style == 1) {
        kstep   = 4;
    } else {
        kstep   = 2;
    }

    /* at this point we will use a combination of a sieve and Miller-Rabin */

    if (bbs_style == 1) {
        /* if a mod 4 != 3 subtract the correct value to make it so */
        if ((a->dp[0] & 3) != 3) {
            if ((err = mp_sub_d(a, (a->dp[0] & 3) + 1, a)) != MP_OKAY) {
                return err;
            };
        }
    } else {
        if (mp_iseven(a) == 1) {
            /* force odd */
            if ((err = mp_sub_d(a, 1, a)) != MP_OKAY) {
                return err;
            }
        }
    }

    /* generate the restable */
    for (x = 1; x < PRIME_SIZE; x++) {
        if ((err = mp_mod_d(a, ltm_prime_tab[x], res_tab + x)) != MP_OKAY) {
            return err;
        }
    }

    /* init temp used for Miller-Rabin Testing */
    if ((err = mp_init(&b)) != MP_OKAY) {
        return err;
    }

    for (;;) {
        /* skip to the next non-trivially divisible candidate */
        step = 0;
        do {
            /* y == 1 if any residue was zero [e.g. cannot be prime] */
            y     =  0;

            /* increase step to next candidate */
            step += kstep;

            /* compute the new residue without using division */
            for (x = 1; x < PRIME_SIZE; x++) {
                /* add the step to each residue */
                res_tab[x] += kstep;

                /* subtract the modulus [instead of using division] */
                if (res_tab[x] >= ltm_prime_tab[x]) {
                    res_tab[x]  -= ltm_prime_tab[x];
                }

                /* set flag if zero */
                if (res_tab[x] == 0) {
                    y = 1;
                }
            }
        } while (y == 1 && step < ((((mp_digit)1)<<DIGIT_BIT) - kstep));

        /* add the step */
        if ((err = mp_add_d(a, step, a)) != MP_OKAY) {
            goto LBL_ERR;
        }

        /* if didn't pass sieve and step == MAX then skip test */
        if (y == 1 && step >= ((((mp_digit)1)<<DIGIT_BIT) - kstep)) {
            continue;
        }

        /* is this prime? */
        for (x = 0; x < t && x < PRIME_SIZE; x++) {
            mp_set(&b, ltm_prime_tab[x]);
            if ((err = mp_prime_miller_rabin(a, &b, &res)) != MP_OKAY) {
                goto LBL_ERR;
            }
            if (res == MP_NO) {
                break;
            }
        }

        if (res == MP_YES) {
            break;
        }
    }

    err = MP_OKAY;
LBL_ERR:
    mp_clear(&b);
    return err;
}
Beispiel #26
0
static SECStatus
rsa_build_from_primes(mp_int *p, mp_int *q, 
		mp_int *e, PRBool needPublicExponent, 
		mp_int *d, PRBool needPrivateExponent,
		RSAPrivateKey *key, unsigned int keySizeInBits)
{
    mp_int n, phi;
    mp_int psub1, qsub1, tmp;
    mp_err   err = MP_OKAY;
    SECStatus rv = SECSuccess;
    MP_DIGITS(&n)     = 0;
    MP_DIGITS(&phi)   = 0;
    MP_DIGITS(&psub1) = 0;
    MP_DIGITS(&qsub1) = 0;
    MP_DIGITS(&tmp)   = 0;
    CHECK_MPI_OK( mp_init(&n)     );
    CHECK_MPI_OK( mp_init(&phi)   );
    CHECK_MPI_OK( mp_init(&psub1) );
    CHECK_MPI_OK( mp_init(&qsub1) );
    CHECK_MPI_OK( mp_init(&tmp)   );
    /* 1.  Compute n = p*q */
    CHECK_MPI_OK( mp_mul(p, q, &n) );
    /*     verify that the modulus has the desired number of bits */
    if ((unsigned)mpl_significant_bits(&n) != keySizeInBits) {
	PORT_SetError(SEC_ERROR_NEED_RANDOM);
	rv = SECFailure;
	goto cleanup;
    }

    /* at least one exponent must be given */
    PORT_Assert(!(needPublicExponent && needPrivateExponent));

    /* 2.  Compute phi = (p-1)*(q-1) */
    CHECK_MPI_OK( mp_sub_d(p, 1, &psub1) );
    CHECK_MPI_OK( mp_sub_d(q, 1, &qsub1) );
    if (needPublicExponent || needPrivateExponent) {
	CHECK_MPI_OK( mp_mul(&psub1, &qsub1, &phi) );
	/* 3.  Compute d = e**-1 mod(phi) */
	/*     or      e = d**-1 mod(phi) as necessary */
	if (needPublicExponent) {
	    err = mp_invmod(d, &phi, e);
	} else {
	    err = mp_invmod(e, &phi, d);
	}
    } else {
	err = MP_OKAY;
    }
    /*     Verify that phi(n) and e have no common divisors */
    if (err != MP_OKAY) {
	if (err == MP_UNDEF) {
	    PORT_SetError(SEC_ERROR_NEED_RANDOM);
	    err = MP_OKAY; /* to keep PORT_SetError from being called again */
	    rv = SECFailure;
	}
	goto cleanup;
    }

    /* 4.  Compute exponent1 = d mod (p-1) */
    CHECK_MPI_OK( mp_mod(d, &psub1, &tmp) );
    MPINT_TO_SECITEM(&tmp, &key->exponent1, key->arena);
    /* 5.  Compute exponent2 = d mod (q-1) */
    CHECK_MPI_OK( mp_mod(d, &qsub1, &tmp) );
    MPINT_TO_SECITEM(&tmp, &key->exponent2, key->arena);
    /* 6.  Compute coefficient = q**-1 mod p */
    CHECK_MPI_OK( mp_invmod(q, p, &tmp) );
    MPINT_TO_SECITEM(&tmp, &key->coefficient, key->arena);

    /* copy our calculated results, overwrite what is there */
    key->modulus.data = NULL;
    MPINT_TO_SECITEM(&n, &key->modulus, key->arena);
    key->privateExponent.data = NULL;
    MPINT_TO_SECITEM(d, &key->privateExponent, key->arena);
    key->publicExponent.data = NULL;
    MPINT_TO_SECITEM(e, &key->publicExponent, key->arena);
    key->prime1.data = NULL;
    MPINT_TO_SECITEM(p, &key->prime1, key->arena);
    key->prime2.data = NULL;
    MPINT_TO_SECITEM(q, &key->prime2, key->arena);
cleanup:
    mp_clear(&n);
    mp_clear(&phi);
    mp_clear(&psub1);
    mp_clear(&qsub1);
    mp_clear(&tmp);
    if (err) {
	MP_TO_SEC_ERROR(err);
	rv = SECFailure;
    }
    return rv;
}
Beispiel #27
0
/**
  Import an RSAPublicKey or RSAPrivateKey [two-prime only, only support >= 1024-bit keys, defined in LTC_PKCS #1 v2.1]
  @param in      The packet to import from
  @param inlen   It's length (octets)
  @param key     [out] Destination for newly imported key
  @return CRYPT_OK if successful, upon error allocated memory is freed
*/
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key)
{
   int           err;
   void         *zero;
   unsigned char *tmpbuf;
   unsigned long  t, x, y, z, tmpoid[16];
   ltc_asn1_list ssl_pubkey_hashoid[2];
   ltc_asn1_list ssl_pubkey[2];

   LTC_ARGCHK(in          != NULL);
   LTC_ARGCHK(key         != NULL);
   LTC_ARGCHK(ltc_mp.name != NULL);

   /* init key */
   if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ, 
                            &key->dP, &key->qP, &key->p, &key->q, NULL)) != CRYPT_OK) {
      return err;
   }

   /* see if the OpenSSL DER format RSA public key will work */
   tmpbuf = XCALLOC(1, MAX_RSA_SIZE*8);
   if (tmpbuf == NULL) {
       err = CRYPT_MEM;
       goto LBL_ERR;
   }

   /* this includes the internal hash ID and optional params (NULL in this case) */
   LTC_SET_ASN1(ssl_pubkey_hashoid, 0, LTC_ASN1_OBJECT_IDENTIFIER, tmpoid,                sizeof(tmpoid)/sizeof(tmpoid[0]));   
   LTC_SET_ASN1(ssl_pubkey_hashoid, 1, LTC_ASN1_NULL,              NULL,                  0);

   /* the actual format of the SSL DER key is odd, it stores a RSAPublicKey in a **BIT** string ... so we have to extract it
      then proceed to convert bit to octet 
    */
   LTC_SET_ASN1(ssl_pubkey, 0,         LTC_ASN1_SEQUENCE,          &ssl_pubkey_hashoid,   2);
   LTC_SET_ASN1(ssl_pubkey, 1,         LTC_ASN1_BIT_STRING,        tmpbuf,                MAX_RSA_SIZE*8);

   if (der_decode_sequence(in, inlen,
                           ssl_pubkey, 2UL) == CRYPT_OK) {

      /* ok now we have to reassemble the BIT STRING to an OCTET STRING.  Thanks OpenSSL... */
      for (t = y = z = x = 0; x < ssl_pubkey[1].size; x++) {
          y = (y << 1) | tmpbuf[x];
          if (++z == 8) {
             tmpbuf[t++] = (unsigned char)y;
             y           = 0;
             z           = 0;
          }
      }

      /* now it should be SEQUENCE { INTEGER, INTEGER } */
      if ((err = der_decode_sequence_multi(tmpbuf, t,
                                           LTC_ASN1_INTEGER, 1UL, key->N, 
                                           LTC_ASN1_INTEGER, 1UL, key->e, 
                                           LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         XFREE(tmpbuf);
         goto LBL_ERR;
      }
      XFREE(tmpbuf);
      key->type = PK_PUBLIC;
      return CRYPT_OK;
   }
   XFREE(tmpbuf);

   /* not SSL public key, try to match against LTC_PKCS #1 standards */
   if ((err = der_decode_sequence_multi(in, inlen, 
                                  LTC_ASN1_INTEGER, 1UL, key->N, 
                                  LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
      goto LBL_ERR;
   }

   if (mp_cmp_d(key->N, 0) == LTC_MP_EQ) {
      if ((err = mp_init(&zero)) != CRYPT_OK) { 
         goto LBL_ERR;
      }
      /* it's a private key */
      if ((err = der_decode_sequence_multi(in, inlen, 
                          LTC_ASN1_INTEGER, 1UL, zero, 
                          LTC_ASN1_INTEGER, 1UL, key->N, 
                          LTC_ASN1_INTEGER, 1UL, key->e,
                          LTC_ASN1_INTEGER, 1UL, key->d, 
                          LTC_ASN1_INTEGER, 1UL, key->p, 
                          LTC_ASN1_INTEGER, 1UL, key->q, 
                          LTC_ASN1_INTEGER, 1UL, key->dP,
                          LTC_ASN1_INTEGER, 1UL, key->dQ, 
                          LTC_ASN1_INTEGER, 1UL, key->qP, 
                          LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         mp_clear(zero);
         goto LBL_ERR;
      }
      mp_clear(zero);
      key->type = PK_PRIVATE;
   } else if (mp_cmp_d(key->N, 1) == LTC_MP_EQ) {
      /* we don't support multi-prime RSA */
      err = CRYPT_PK_INVALID_TYPE;
      goto LBL_ERR;
   } else {
      /* it's a public key and we lack e */
      if ((err = der_decode_sequence_multi(in, inlen, 
                                     LTC_ASN1_INTEGER, 1UL, key->N, 
                                     LTC_ASN1_INTEGER, 1UL, key->e, 
                                     LTC_ASN1_EOL,     0UL, NULL)) != CRYPT_OK) {
         goto LBL_ERR;
      }
      key->type = PK_PUBLIC;
   }
   return CRYPT_OK;
LBL_ERR:
   mp_clear_multi(key->d,  key->e, key->N, key->dQ, key->dP, key->qP, key->p, key->q, NULL);
   return err;
}
Beispiel #28
0
void bp4p_init(int *argc, char **argv[])
{
#ifdef MPI
    mp_init(argc, argv);
#endif
}
Beispiel #29
0
/* Initialize a new instance. */
static void initialize(PARROT_INTERP, STable *st, void *data) {
    P6bigintBody *body = (P6bigintBody *)data;
    mp_init(&body->i);
    mp_zero(&body->i);
}
Beispiel #30
0
int main()
{
  cout  << setiosflags(ios::uppercase);
  
  ofstream out1("Daten_ErrorGauss.out");
  out1 << setiosflags(ios::uppercase);
  
  ofstream out("LIP_Error.out");
  out << setiosflags(ios::uppercase);

  ofstream outs("Y2D_Error.out");
  outs  << setiosflags(ios::uppercase);
  
  ofstream rout("REGLIP_ErrorGauss.out");
  rout  << setiosflags(ios::uppercase);

  ofstream lout("L2-NormGauss.out");
  lout  << setiosflags(ios::uppercase);
  
  cout << "*** Error: Imaginaerteilgleichung ***" << endl;
  cout << "*** Filter: Gauss ***" << endl;

  mp_init();
  cout << "*** Precision = " << mpipl << " ***" << endl;
  

  int M, N, MD;
  double xa, xb, x1, x2, xr1, xr2, h, step, step2, b1, dfactor, dpi;
  mp_real b, mpx1, mpx2, mpstep, mpx;

  dpi = 4.0 * atan(1.0);

  mp_real pi = mppic; // pi aus der Bibliothek !!!
  mp_real pi2 = pi * pi;
  static mp_real factor;


  cin >> b1;
  cin >> xa >> xb >> MD;
  cin >> x1 >> x2 >> M;  
  cin >> xr1 >> xr2 >> N ;
  
  cout << '\v';

  /* KERNELARRY ANFANG */

  mp_real* const mpregKern = new mp_real [M+1];
  b = mp_real(b1);
  mpx1 = mp_real(x1);
  mpx2 = mp_real(x2);

  mpstep = (mpx2 - mpx1)/mp_real(M);  
  
  /* Vorfaktor */
  factor = mp_real(2.0)*b/power(pi,mp_real(1.5));
  factor *= exp(mp_real(0.25) * pi2 * b * b);
  
  dfactor = 2.0 * (b1/pow(dpi,1.5)) * exp(b1*b1*dpi*dpi*.25);

  cout << "*** Begin: Init. Kernel *** " << endl;
    
  cout << "b1  = " << b1  << endl;
  cout << "b  = " <<  b ;
  cout << "x1  = " << x1 << endl;  /* Anfangs-/Endpunkt der Regularisierung */
  cout << "x2  = " << x2 << endl;
  cout << "M   = " << M  << endl; 
  cout << "h   = " << mpstep;
  cout << "factor = " << factor ;
  cout << "dfactor = " << dfactor << endl;

  for(int i = 0; i <= M; i++) 
    {
      mpx = mpx1 + i * mpstep;
      mpregKern[i] = mpregkerne2(mpx, b);
    }

  cout << "*** End: Init. Kernel *** " << endl;

  /* KERNELARRY ENDE */

  double x0, datlinpol, Error_splint, DataError, e2core;

  /* Index der Vektoren beginnt mit 1 und *nicht* mit 0 */
  
  double* y2d = dvector(1,MD);  /* 2.Ableitung der SPL-Funktion */
  double* data = dvector(1,MD); /* Datenvektor */
  double* x = dvector(1,MD);    /* x-Vektor */
  
  /* Datenarrays fuellen */

  h = (xb - xa)/(MD - 1);
  double rho = MD/(xb -xa);

  cout << '\v';
  cout << "*** Begin: Init. Data-Array ***" << endl;
  cout << "xa  = " << xa << endl;   /* Anfangs-/Endpunkte der Daten */
  cout << "xb  = " << xb << endl;
  cout << "MD  = " << MD  << endl;  /* Zahl der Datenpunkte */
  cout << "h   = " << h  << endl;
  cout << "rho = " << rho  << endl;
  x[1] = xa;
  data[1] = e2data(xa);

  for(int i = 2; i <= MD ; i++)
    {
      x[i] = xa + (i-1) * h;
      data[i] = e2data(x[i]);
    }

  x[MD] = xb;
  data[MD] = e2data(xb);
  
  cout << "*** End: Init. Data-Array ***" << endl;
  cout << '\v' ;

  /* Kontrollausgabe, Datenausgabe */
  for(int i = 1; i <= MD; i++)
    {
      DataError = fabs(data[i] - e2(x[i]))/fabs(e2(x[i]));
      DataError *= 100.0;
      out1 << i << '\t' << x[i] << '\t' << data[i] << '\t' << e2(x[i]) << '\t' << DataError << endl;
    }

  cout << "*** Begin: Interpol. *** " << endl;

  intlinear(x,data,MD,y2d);

  for(int i = 1; i <= MD; i++) outs << i << '\t'  << y2d[i] << endl;

  cout << "*** End:   Interpol. *** " << endl; 
  cout << '\v';

  
  /* L2-Norm des Datenfehlers, incl. Interpolationsfehler */
  double epsx0, eps2data;
  epsx0 = 0.0;

  for(int j = 0; j <= M; j++)
    {
      step = dble(mpstep);
      x0 = x1 + j * step;
      
      datlinpol = linint(x,data,y2d,MD,x0);
      e2core  = e2(x0);
      Error_splint = fabs(datlinpol - e2core)/fabs(e2core);
      Error_splint *= 100.0;

      eps2data = (datlinpol - e2core)*(datlinpol - e2core);      
      epsx0 += eps2data;

      out << x0 << '\t' <<  datlinpol << '\t' << e2core << '\t' << Error_splint << endl;
      
    }
  epsx0 *= step;

  /* REGULARISIERUNG */
 
  double xi;

  mp_real mp_regsum, mpdata, mpError, mpreg;
  double regsum, Reg;
  double Error;

  step2 = (xr2 - xr1)/N;

  cout <<"*** Begin: Error Regularisation ***" << endl;
  cout << "b1  = " << b1  << endl;
  cout << "b  = " <<  b ;
  cout << "x1 = " << xr1 << endl;
  cout << "x2 = " << xr2 << endl;
  cout << "N  = " << N  << endl;
  cout << "h  = " << step2 << endl;
  cout << "*** L2-Datenfehler = " << epsx0 << endl;

  cout << '\v' ;

  mpError = mp_real(0.0); //L2 - Norm des Fehlers

  for(int jj = 0; jj <= N; jj++)
  {
    mp_regsum = mp_real(0.0);
    x0 = xr1 + jj * step2;
    
    for(int j = 0; j <= M; j++)
      {
	xi = x1 + j * step;
	xi = x0 - xi;
	/* Differenz: Interpolierte Daten - exakte Funktion */
	datlinpol = linint(x,data,y2d,MD,xi) - e2(xi);
	mpdata = mp_real(datlinpol);
	mp_regsum += mpregKern[j] * mpdata;
	
      }
    mp_regsum *= mpstep;
    mp_regsum *= factor;

    /* Berechnung des quadrates der L2-Norm des Fehlereinflusses */
    //mpError += step2*exp(x0)*mp_regsum*mp_regsum;

    /* x0 = 0, entspricht nicht! der Norm im urspr. Raum!!! 
     Hier ersteinmal nur zu Testzwecken! */
    mpError += step2*mp_regsum*mp_regsum; 

    mpreg  = mpRegexakt(mp_real(x0),b);
    regsum = dble(mp_regsum);
    Reg    = dble(mpreg);

    cout << x0    << endl;
    cout << mpreg << endl;
    //    cout << mpreg << mp_regsum << mpError << endl;

    Error = dble(mpError);
  
    rout << x0 << '\t' << regsum << '\t' << Reg << '\t' << Reg + regsum <<'\t' << b1 << endl; 
    
  }
  cout << "*** L2-Norm mpError ***" << endl; 
  cout << mpError << endl;
 
  cout << "*** End: Error Regularisation ***" << endl;
  cout << '\v';
  cout << "*** L2-Datenfehler = " << epsx0 << " ***" << endl;
  cout << "*** L2-Norm Error  = " << Error << " ***" << endl; 

  lout << "b " << '\t' << "L2-Datenfehler" << '\t' << " L2-Error" << endl;
  lout << b1 << '\t' << epsx0 << '\t' << Error << endl;
 
  free_dvector(y2d,1,MD);
  free_dvector(data,1,MD);
  free_dvector(x,1,MD);
  delete [] mpregKern;

  return 0;
}