/* Generates a new EC key pair. The private key is a supplied * value and the public key is the result of performing a scalar * point multiplication of that value with the curve's base point. */ SECStatus ec_NewKey(ECParams *ecParams, ECPrivateKey **privKey, const unsigned char *privKeyBytes, int privKeyLen) { SECStatus rv = SECFailure; #ifdef NSS_ENABLE_ECC PRArenaPool *arena; ECPrivateKey *key; mp_int k; mp_err err = MP_OKAY; int len; #if EC_DEBUG printf("ec_NewKey called\n"); #endif MP_DIGITS(&k) = 0; if (!ecParams || !privKey || !privKeyBytes || (privKeyLen < 0)) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } /* Initialize an arena for the EC key. */ if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE))) return SECFailure; key = (ECPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(ECPrivateKey)); if (!key) { PORT_FreeArena(arena, PR_TRUE); return SECFailure; } /* Set the version number (SEC 1 section C.4 says it should be 1) */ SECITEM_AllocItem(arena, &key->version, 1); key->version.data[0] = 1; /* Copy all of the fields from the ECParams argument to the * ECParams structure within the private key. */ key->ecParams.arena = arena; key->ecParams.type = ecParams->type; key->ecParams.fieldID.size = ecParams->fieldID.size; key->ecParams.fieldID.type = ecParams->fieldID.type; if (ecParams->fieldID.type == ec_field_GFp) { CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.fieldID.u.prime, &ecParams->fieldID.u.prime)); } else { CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.fieldID.u.poly, &ecParams->fieldID.u.poly)); } key->ecParams.fieldID.k1 = ecParams->fieldID.k1; key->ecParams.fieldID.k2 = ecParams->fieldID.k2; key->ecParams.fieldID.k3 = ecParams->fieldID.k3; CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.a, &ecParams->curve.a)); CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.b, &ecParams->curve.b)); CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.seed, &ecParams->curve.seed)); CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.base, &ecParams->base)); CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.order, &ecParams->order)); key->ecParams.cofactor = ecParams->cofactor; CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.DEREncoding, &ecParams->DEREncoding)); key->ecParams.name = ecParams->name; CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curveOID, &ecParams->curveOID)); len = (ecParams->fieldID.size + 7) >> 3; SECITEM_AllocItem(arena, &key->publicValue, 2*len + 1); len = ecParams->order.len; SECITEM_AllocItem(arena, &key->privateValue, len); /* Copy private key */ if (privKeyLen >= len) { memcpy(key->privateValue.data, privKeyBytes, len); } else { memset(key->privateValue.data, 0, (len - privKeyLen)); memcpy(key->privateValue.data + (len - privKeyLen), privKeyBytes, privKeyLen); } /* Compute corresponding public key */ CHECK_MPI_OK( mp_init(&k) ); CHECK_MPI_OK( mp_read_unsigned_octets(&k, key->privateValue.data, (mp_size) len) ); rv = ec_points_mul(ecParams, &k, NULL, NULL, &(key->publicValue)); if (rv != SECSuccess) goto cleanup; *privKey = key; cleanup: mp_clear(&k); if (rv) PORT_FreeArena(arena, PR_TRUE); #if EC_DEBUG printf("ec_NewKey returning %s\n", (rv == SECSuccess) ? "success" : "failure"); #endif #else PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); #endif /* NSS_ENABLE_ECC */ return rv; }
/* Validates an EC public key as described in Section 5.2.2 of * X9.62. The ECDH primitive when used without the cofactor does * not address small subgroup attacks, which may occur when the * public key is not valid. These attacks can be prevented by * validating the public key before using ECDH. */ SECStatus EC_ValidatePublicKey(ECParams *ecParams, SECItem *publicValue) { #ifdef NSS_ENABLE_ECC mp_int Px, Py; ECGroup *group = NULL; SECStatus rv = SECFailure; mp_err err = MP_OKAY; int len; if (!ecParams || !publicValue) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } /* NOTE: We only support uncompressed points for now */ len = (ecParams->fieldID.size + 7) >> 3; if (publicValue->data[0] != EC_POINT_FORM_UNCOMPRESSED) { PORT_SetError(SEC_ERROR_UNSUPPORTED_EC_POINT_FORM); return SECFailure; } else if (publicValue->len != (2 * len + 1)) { PORT_SetError(SEC_ERROR_BAD_KEY); return SECFailure; } MP_DIGITS(&Px) = 0; MP_DIGITS(&Py) = 0; CHECK_MPI_OK( mp_init(&Px) ); CHECK_MPI_OK( mp_init(&Py) ); /* Initialize Px and Py */ CHECK_MPI_OK( mp_read_unsigned_octets(&Px, publicValue->data + 1, (mp_size) len) ); CHECK_MPI_OK( mp_read_unsigned_octets(&Py, publicValue->data + 1 + len, (mp_size) len) ); /* construct from named params */ group = ECGroup_fromName(ecParams->name); if (group == NULL) { /* * ECGroup_fromName fails if ecParams->name is not a valid * ECCurveName value, or if we run out of memory, or perhaps * for other reasons. Unfortunately if ecParams->name is a * valid ECCurveName value, we don't know what the right error * code should be because ECGroup_fromName doesn't return an * error code to the caller. Set err to MP_UNDEF because * that's what ECGroup_fromName uses internally. */ if ((ecParams->name <= ECCurve_noName) || (ecParams->name >= ECCurve_pastLastCurve)) { err = MP_BADARG; } else { err = MP_UNDEF; } goto cleanup; } /* validate public point */ if ((err = ECPoint_validate(group, &Px, &Py)) < MP_YES) { if (err == MP_NO) { PORT_SetError(SEC_ERROR_BAD_KEY); rv = SECFailure; err = MP_OKAY; /* don't change the error code */ } goto cleanup; } rv = SECSuccess; cleanup: ECGroup_free(group); mp_clear(&Px); mp_clear(&Py); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; #else PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); return SECFailure; #endif /* NSS_ENABLE_ECC */ }
/* Performs basic tests of elliptic curve cryptography over binary * polynomial fields. If tests fail, then it prints an error message, * aborts, and returns an error code. Otherwise, returns 0. */ int ectest_curve_GF2m(ECGroup *group, int ectestPrint, int ectestTime, int generic) { mp_int one, order_1, gx, gy, rx, ry, n; int size; mp_err res; char s[1000]; /* initialize values */ MP_CHECKOK(mp_init(&one)); MP_CHECKOK(mp_init(&order_1)); MP_CHECKOK(mp_init(&gx)); MP_CHECKOK(mp_init(&gy)); MP_CHECKOK(mp_init(&rx)); MP_CHECKOK(mp_init(&ry)); MP_CHECKOK(mp_init(&n)); MP_CHECKOK(mp_set_int(&one, 1)); MP_CHECKOK(mp_sub(&group->order, &one, &order_1)); /* encode base point */ if (group->meth->field_dec) { MP_CHECKOK(group->meth->field_dec(&group->genx, &gx, group->meth)); MP_CHECKOK(group->meth->field_dec(&group->geny, &gy, group->meth)); } else { MP_CHECKOK(mp_copy(&group->genx, &gx)); MP_CHECKOK(mp_copy(&group->geny, &gy)); } if (ectestPrint) { /* output base point */ printf(" base point P:\n"); MP_CHECKOK(mp_toradix(&gx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&gy, s, 16)); printf(" %s\n", s); if (group->meth->field_enc) { printf(" base point P (encoded):\n"); MP_CHECKOK(mp_toradix(&group->genx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&group->geny, s, 16)); printf(" %s\n", s); } } #ifdef ECL_ENABLE_GF2M_PT_MUL_AFF /* multiply base point by order - 1 and check for negative of base * point */ MP_CHECKOK(ec_GF2m_pt_mul_aff(&order_1, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order-1)*P (affine):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(group->meth->field_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &group->genx) != 0) || (mp_cmp(&ry, &group->geny) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } #endif /* multiply base point by order - 1 and check for negative of base * point */ MP_CHECKOK(ec_GF2m_pt_mul_mont(&order_1, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order-1)*P (montgomery):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(group->meth->field_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &group->genx) != 0) || (mp_cmp(&ry, &group->geny) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } #ifdef ECL_ENABLE_GF2M_PROJ /* multiply base point by order - 1 and check for negative of base * point */ MP_CHECKOK(ec_GF2m_pt_mul_proj(&order_1, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order-1)*P (projective):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(group->meth->field_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &group->genx) != 0) || (mp_cmp(&ry, &group->geny) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } #endif /* multiply base point by order - 1 and check for negative of base * point */ MP_CHECKOK(ECPoint_mul(group, &order_1, NULL, NULL, &rx, &ry)); if (ectestPrint) { printf(" (order-1)*P (ECPoint_mul):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(ec_GF2m_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } /* multiply base point by order - 1 and check for negative of base * point */ MP_CHECKOK(ECPoint_mul(group, &order_1, &gx, &gy, &rx, &ry)); if (ectestPrint) { printf(" (order-1)*P (ECPoint_mul):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(ec_GF2m_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } #ifdef ECL_ENABLE_GF2M_PT_MUL_AFF /* multiply base point by order and check for point at infinity */ MP_CHECKOK(ec_GF2m_pt_mul_aff(&group->order, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order)*P (affine):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } if (ec_GF2m_pt_is_inf_aff(&rx, &ry) != MP_YES) { printf(" Error: invalid result (expected point at infinity).\n"); res = MP_NO; goto CLEANUP; } #endif /* multiply base point by order and check for point at infinity */ MP_CHECKOK(ec_GF2m_pt_mul_mont(&group->order, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order)*P (montgomery):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } if (ec_GF2m_pt_is_inf_aff(&rx, &ry) != MP_YES) { printf(" Error: invalid result (expected point at infinity).\n"); res = MP_NO; goto CLEANUP; } #ifdef ECL_ENABLE_GF2M_PROJ /* multiply base point by order and check for point at infinity */ MP_CHECKOK(ec_GF2m_pt_mul_proj(&group->order, &group->genx, &group->geny, &rx, &ry, group)); if (ectestPrint) { printf(" (order)*P (projective):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } if (ec_GF2m_pt_is_inf_aff(&rx, &ry) != MP_YES) { printf(" Error: invalid result (expected point at infinity).\n"); res = MP_NO; goto CLEANUP; } #endif /* multiply base point by order and check for point at infinity */ MP_CHECKOK(ECPoint_mul(group, &group->order, NULL, NULL, &rx, &ry)); if (ectestPrint) { printf(" (order)*P (ECPoint_mul):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } if (ec_GF2m_pt_is_inf_aff(&rx, &ry) != MP_YES) { printf(" Error: invalid result (expected point at infinity).\n"); res = MP_NO; goto CLEANUP; } /* multiply base point by order and check for point at infinity */ MP_CHECKOK(ECPoint_mul(group, &group->order, &gx, &gy, &rx, &ry)); if (ectestPrint) { printf(" (order)*P (ECPoint_mul):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } if (ec_GF2m_pt_is_inf_aff(&rx, &ry) != MP_YES) { printf(" Error: invalid result (expected point at infinity).\n"); res = MP_NO; goto CLEANUP; } /* check that (order-1)P + (order-1)P + P == (order-1)P */ MP_CHECKOK(ECPoints_mul(group, &order_1, &order_1, &gx, &gy, &rx, &ry)); MP_CHECKOK(ECPoints_mul(group, &one, &one, &rx, &ry, &rx, &ry)); if (ectestPrint) { printf(" (order-1)*P + (order-1)*P + P == (order-1)*P (ECPoints_mul):\n"); MP_CHECKOK(mp_toradix(&rx, s, 16)); printf(" %s\n", s); MP_CHECKOK(mp_toradix(&ry, s, 16)); printf(" %s\n", s); } MP_CHECKOK(ec_GF2m_add(&ry, &rx, &ry, group->meth)); if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) { printf(" Error: invalid result (expected (- base point)).\n"); res = MP_NO; goto CLEANUP; } /* test validate_point function */ if (ECPoint_validate(group, &gx, &gy) != MP_YES) { printf(" Error: validate point on base point failed.\n"); res = MP_NO; goto CLEANUP; } MP_CHECKOK(mp_add_d(&gy, 1, &ry)); if (ECPoint_validate(group, &gx, &ry) != MP_NO) { printf(" Error: validate point on invalid point passed.\n"); res = MP_NO; goto CLEANUP; } if (ectestTime) { /* compute random scalar */ size = mpl_significant_bits(&group->meth->irr); if (size < MP_OKAY) { goto CLEANUP; } MP_CHECKOK(mpp_random_size(&n, (size + ECL_BITS - 1) / ECL_BITS)); MP_CHECKOK(group->meth->field_mod(&n, &n, group->meth)); /* timed test */ if (generic) { #ifdef ECL_ENABLE_GF2M_PT_MUL_AFF M_TimeOperation(MP_CHECKOK(ec_GF2m_pt_mul_aff(&n, &group->genx, &group->geny, &rx, &ry, group)), 100); #endif M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, NULL, NULL, &rx, &ry)), 100); M_TimeOperation(MP_CHECKOK(ECPoints_mul(group, &n, &n, &gx, &gy, &rx, &ry)), 100); } else { M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, NULL, NULL, &rx, &ry)), 100); M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, &gx, &gy, &rx, &ry)), 100); M_TimeOperation(MP_CHECKOK(ECPoints_mul(group, &n, &n, &gx, &gy, &rx, &ry)), 100); } } CLEANUP: mp_clear(&one); mp_clear(&order_1); mp_clear(&gx); mp_clear(&gy); mp_clear(&rx); mp_clear(&ry); mp_clear(&n); if (res != MP_OKAY) { printf(" Error: exiting with error value %i\n", res); } return res; }
/* ** 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; }
/* stores a bignum as a ASCII string in a given radix (2..64) * * Stores upto maxlen-1 chars and always a NULL byte */ int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen) { int res, digs; mp_int t; mp_digit d; char *_s = str; /* check range of the maxlen, radix */ if (maxlen < 2 || radix < 2 || radix > 64) { return MP_VAL; } /* quick out if its zero */ if (mp_iszero(a) == MP_YES) { *str++ = '0'; *str = '\0'; return MP_OKAY; } if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } /* if it is negative output a - */ if (t.sign == MP_NEG) { /* we have to reverse our digits later... but not the - sign!! */ ++_s; /* store the flag and mark the number as positive */ *str++ = '-'; t.sign = MP_ZPOS; /* subtract a char */ --maxlen; } digs = 0; while (mp_iszero (&t) == 0) { if (--maxlen < 1) { /* no more room */ break; } if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { mp_clear (&t); return res; } *str++ = mp_s_rmap[d]; ++digs; } /* reverse the digits of the string. In this case _s points * to the first digit [exluding the sign] of the number */ bn_reverse ((unsigned char *)_s, digs); /* append a NULL so the string is properly terminated */ *str = '\0'; mp_clear (&t); return MP_OKAY; }
/* * 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; }
/* * 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) { PRArenaPool *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 * 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 * 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 * 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; }
/* 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; }
/* Computes the ECDSA signature (a concatenation of two values r and s) * on the digest using the given key and the random value kb (used in * computing s). */ SECStatus ECDSA_SignDigestWithSeed(ECPrivateKey *key, SECItem *signature, const SECItem *digest, const unsigned char *kb, const int kblen) { SECStatus rv = SECFailure; #ifdef NSS_ENABLE_ECC mp_int x1; mp_int d, k; /* private key, random integer */ mp_int r, s; /* tuple (r, s) is the signature */ mp_int n; mp_err err = MP_OKAY; ECParams *ecParams = NULL; SECItem kGpoint = { siBuffer, NULL, 0}; int flen = 0; /* length in bytes of the field size */ unsigned olen; /* length in bytes of the base point order */ unsigned obits; /* length in bits of the base point order */ #if EC_DEBUG char mpstr[256]; #endif /* Initialize MPI integers. */ /* must happen before the first potential call to cleanup */ MP_DIGITS(&x1) = 0; MP_DIGITS(&d) = 0; MP_DIGITS(&k) = 0; MP_DIGITS(&r) = 0; MP_DIGITS(&s) = 0; MP_DIGITS(&n) = 0; /* Check args */ if (!key || !signature || !digest || !kb || (kblen < 0)) { PORT_SetError(SEC_ERROR_INVALID_ARGS); goto cleanup; } ecParams = &(key->ecParams); flen = (ecParams->fieldID.size + 7) >> 3; olen = ecParams->order.len; if (signature->data == NULL) { /* a call to get the signature length only */ goto finish; } if (signature->len < 2*olen) { PORT_SetError(SEC_ERROR_OUTPUT_LEN); goto cleanup; } CHECK_MPI_OK( mp_init(&x1) ); CHECK_MPI_OK( mp_init(&d) ); CHECK_MPI_OK( mp_init(&k) ); CHECK_MPI_OK( mp_init(&r) ); CHECK_MPI_OK( mp_init(&s) ); CHECK_MPI_OK( mp_init(&n) ); SECITEM_TO_MPINT( ecParams->order, &n ); SECITEM_TO_MPINT( key->privateValue, &d ); CHECK_MPI_OK( mp_read_unsigned_octets(&k, kb, kblen) ); /* Make sure k is in the interval [1, n-1] */ if ((mp_cmp_z(&k) <= 0) || (mp_cmp(&k, &n) >= 0)) { #if EC_DEBUG printf("k is outside [1, n-1]\n"); mp_tohex(&k, mpstr); printf("k : %s \n", mpstr); mp_tohex(&n, mpstr); printf("n : %s \n", mpstr); #endif PORT_SetError(SEC_ERROR_NEED_RANDOM); goto cleanup; } /* ** We do not want timing information to leak the length of k, ** so we compute k*G using an equivalent scalar of fixed ** bit-length. ** Fix based on patch for ECDSA timing attack in the paper ** by Billy Bob Brumley and Nicola Tuveri at ** http://eprint.iacr.org/2011/232 ** ** How do we convert k to a value of a fixed bit-length? ** k starts off as an integer satisfying 0 <= k < n. Hence, ** n <= k+n < 2n, which means k+n has either the same number ** of bits as n or one more bit than n. If k+n has the same ** number of bits as n, the second addition ensures that the ** final value has exactly one more bit than n. Thus, we ** always end up with a value that exactly one more bit than n. */ CHECK_MPI_OK( mp_add(&k, &n, &k) ); if (mpl_significant_bits(&k) <= mpl_significant_bits(&n)) { CHECK_MPI_OK( mp_add(&k, &n, &k) ); } /* ** ANSI X9.62, Section 5.3.2, Step 2 ** ** Compute kG */ kGpoint.len = 2*flen + 1; kGpoint.data = PORT_Alloc(2*flen + 1); if ((kGpoint.data == NULL) || (ec_points_mul(ecParams, &k, NULL, NULL, &kGpoint) != SECSuccess)) goto cleanup; /* ** ANSI X9.62, Section 5.3.3, Step 1 ** ** Extract the x co-ordinate of kG into x1 */ CHECK_MPI_OK( mp_read_unsigned_octets(&x1, kGpoint.data + 1, (mp_size) flen) ); /* ** ANSI X9.62, Section 5.3.3, Step 2 ** ** r = x1 mod n NOTE: n is the order of the curve */ CHECK_MPI_OK( mp_mod(&x1, &n, &r) ); /* ** ANSI X9.62, Section 5.3.3, Step 3 ** ** verify r != 0 */ if (mp_cmp_z(&r) == 0) { PORT_SetError(SEC_ERROR_NEED_RANDOM); goto cleanup; } /* ** ANSI X9.62, Section 5.3.3, Step 4 ** ** s = (k**-1 * (HASH(M) + d*r)) mod n */ SECITEM_TO_MPINT(*digest, &s); /* s = HASH(M) */ /* In the definition of EC signing, digests are truncated * to the length of n in bits. * (see SEC 1 "Elliptic Curve Digit Signature Algorithm" section 4.1.*/ CHECK_MPI_OK( (obits = mpl_significant_bits(&n)) ); if (digest->len*8 > obits) { mpl_rsh(&s,&s,digest->len*8 - obits); } #if EC_DEBUG mp_todecimal(&n, mpstr); printf("n : %s (dec)\n", mpstr); mp_todecimal(&d, mpstr); printf("d : %s (dec)\n", mpstr); mp_tohex(&x1, mpstr); printf("x1: %s\n", mpstr); mp_todecimal(&s, mpstr); printf("digest: %s (decimal)\n", mpstr); mp_todecimal(&r, mpstr); printf("r : %s (dec)\n", mpstr); mp_tohex(&r, mpstr); printf("r : %s\n", mpstr); #endif CHECK_MPI_OK( mp_invmod(&k, &n, &k) ); /* k = k**-1 mod n */ CHECK_MPI_OK( mp_mulmod(&d, &r, &n, &d) ); /* d = d * r mod n */ CHECK_MPI_OK( mp_addmod(&s, &d, &n, &s) ); /* s = s + d mod n */ CHECK_MPI_OK( mp_mulmod(&s, &k, &n, &s) ); /* s = s * k mod n */ #if EC_DEBUG mp_todecimal(&s, mpstr); printf("s : %s (dec)\n", mpstr); mp_tohex(&s, mpstr); printf("s : %s\n", mpstr); #endif /* ** ANSI X9.62, Section 5.3.3, Step 5 ** ** verify s != 0 */ if (mp_cmp_z(&s) == 0) { PORT_SetError(SEC_ERROR_NEED_RANDOM); goto cleanup; } /* ** ** Signature is tuple (r, s) */ CHECK_MPI_OK( mp_to_fixlen_octets(&r, signature->data, olen) ); CHECK_MPI_OK( mp_to_fixlen_octets(&s, signature->data + olen, olen) ); finish: signature->len = 2*olen; rv = SECSuccess; err = MP_OKAY; cleanup: mp_clear(&x1); mp_clear(&d); mp_clear(&k); mp_clear(&r); mp_clear(&s); mp_clear(&n); if (kGpoint.data) { PORT_ZFree(kGpoint.data, 2*flen + 1); } if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } #if EC_DEBUG printf("ECDSA signing with seed %s\n", (rv == SECSuccess) ? "succeeded" : "failed"); #endif #else PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); #endif /* NSS_ENABLE_ECC */ return rv; }
static int crtmgr_rsa_verify(cli_crt *x509, mp_int *sig, cli_crt_hashtype hashtype, const uint8_t *refhash) { int keylen = mp_unsigned_bin_size(&x509->n), siglen = mp_unsigned_bin_size(sig); int ret, j, objlen, hashlen = (hashtype == CLI_SHA1RSA) ? SHA1_HASH_SIZE : 16; uint8_t d[513]; mp_int x; if((ret = mp_init(&x))) { cli_errmsg("crtmgr_rsa_verify: mp_init failed with %d\n", ret); return 1; } do { if(MAX(keylen, siglen) - MIN(keylen, siglen) > 1) break; if((ret = mp_exptmod(sig, &x509->e, &x509->n, &x))) { cli_warnmsg("crtmgr_rsa_verify: verification failed: mp_exptmod failed with %d\n", ret); break; } if(mp_unsigned_bin_size(&x) != keylen - 1) break; if((ret = mp_to_unsigned_bin(&x, d))) { cli_warnmsg("crtmgr_rsa_verify: mp_unsigned_bin_size failed with %d\n", ret); break; } if(*d != 1) /* block type 1 */ break; keylen -= 1; /* 0xff padding */ for(j=1; j<keylen-2; j++) if(d[j] != 0xff) break; if(j == keylen - 2) break; if(d[j] != 0) /* 0x00 separator */ break; j++; keylen -= j; /* asn1 size */ if(keylen < hashlen) break; if(keylen > hashlen) { /* hash is asn1 der encoded */ /* SEQ { SEQ { OID, NULL }, OCTET STRING */ if(keylen < 2 || d[j] != 0x30 || d[j+1] + 2 != keylen) break; keylen -= 2; j+=2; if(keylen <2 || d[j] != 0x30) break; objlen = d[j+1]; keylen -= 2; j+=2; if(keylen < objlen) break; if(objlen == 9) { if(hashtype != CLI_SHA1RSA || memcmp(&d[j], "\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00", 9)) { cli_errmsg("crtmgr_rsa_verify: FIXME ACAB - CRYPTO MISSING?\n"); break; } } else if(objlen == 12) { if(hashtype != CLI_MD5RSA || memcmp(&d[j], "\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00", 12)) { cli_errmsg("crtmgr_rsa_verify: FIXME ACAB - CRYPTO MISSING?\n"); break; } } else { cli_errmsg("crtmgr_rsa_verify: FIXME ACAB - CRYPTO MISSING?\n"); break; } keylen -= objlen; j += objlen; if(keylen < 2 || d[j] != 0x04 || d[j+1] != hashlen) break; keylen -= 2; j+=2; if(keylen != hashlen) break; } if(memcmp(&d[j], refhash, hashlen)) break; mp_clear(&x); return 0; } while(0); mp_clear(&x); return 1; }
/* c = |a| * |b| using Karatsuba Multiplication using * three half size multiplications * * Let B represent the radix [e.g. 2**DIGIT_BIT] and * let n represent half of the number of digits in * the min(a,b) * * a = a1 * B**n + a0 * b = b1 * B**n + b0 * * Then, a * b => a1b1 * B**2n + ((a1 + a0)(b1 + b0) - (a0b0 + a1b1)) * B + a0b0 * * Note that a1b1 and a0b0 are used twice and only need to be * computed once. So in total three half size (half # of * digit) multiplications are performed, a0b0, a1b1 and * (a1+b1)(a0+b0) * * Note that a multiplication of half the digits requires * 1/4th the number of single precision multiplications so in * total after one call 25% of the single precision multiplications * are saved. Note also that the call to mp_mul can end up back * in this function if the a0, a1, b0, or b1 are above the threshold. * This is known as divide-and-conquer and leads to the famous * O(N**lg(3)) or O(N**1.584) work which is asymptopically lower than * the standard O(N**2) that the baseline/comba methods use. * Generally though the overhead of this method doesn't pay off * until a certain size (N ~ 80) is reached. */ int mp_karatsuba_mul (mp_int * a, mp_int * b, mp_int * c) { mp_int x0, x1, y0, y1, t1, x0y0, x1y1; int B, err; /* default the return code to an error */ err = MP_MEM; /* min # of digits */ B = MIN (a->used, b->used); /* now divide in two */ B = B >> 1; /* init copy all the temps */ if (mp_init_size (&x0, B) != MP_OKAY) goto ERR; if (mp_init_size (&x1, a->used - B) != MP_OKAY) goto X0; if (mp_init_size (&y0, B) != MP_OKAY) goto X1; if (mp_init_size (&y1, b->used - B) != MP_OKAY) goto Y0; /* init temps */ if (mp_init_size (&t1, B * 2) != MP_OKAY) goto Y1; if (mp_init_size (&x0y0, B * 2) != MP_OKAY) goto T1; if (mp_init_size (&x1y1, B * 2) != MP_OKAY) goto X0Y0; /* now shift the digits */ x0.used = y0.used = B; x1.used = a->used - B; y1.used = b->used - B; { register int x; register mp_digit *tmpa, *tmpb, *tmpx, *tmpy; /* we copy the digits directly instead of using higher level functions * since we also need to shift the digits */ tmpa = a->dp; tmpb = b->dp; tmpx = x0.dp; tmpy = y0.dp; for (x = 0; x < B; x++) { *tmpx++ = *tmpa++; *tmpy++ = *tmpb++; } tmpx = x1.dp; for (x = B; x < a->used; x++) { *tmpx++ = *tmpa++; } tmpy = y1.dp; for (x = B; x < b->used; x++) { *tmpy++ = *tmpb++; } } /* only need to clamp the lower words since by definition the * upper words x1/y1 must have a known number of digits */ mp_clamp (&x0); mp_clamp (&y0); /* now calc the products x0y0 and x1y1 */ /* after this x0 is no longer required, free temp [x0==t2]! */ if (mp_mul (&x0, &y0, &x0y0) != MP_OKAY) goto X1Y1; /* x0y0 = x0*y0 */ if (mp_mul (&x1, &y1, &x1y1) != MP_OKAY) goto X1Y1; /* x1y1 = x1*y1 */ /* now calc x1+x0 and y1+y0 */ if (s_mp_add (&x1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = x1 - x0 */ if (s_mp_add (&y1, &y0, &x0) != MP_OKAY) goto X1Y1; /* t2 = y1 - y0 */ if (mp_mul (&t1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = (x1 + x0) * (y1 + y0) */ /* add x0y0 */ if (mp_add (&x0y0, &x1y1, &x0) != MP_OKAY) goto X1Y1; /* t2 = x0y0 + x1y1 */ if (s_mp_sub (&t1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = (x1+x0)*(y1+y0) - (x1y1 + x0y0) */ /* shift by B */ if (mp_lshd (&t1, B) != MP_OKAY) goto X1Y1; /* t1 = (x0y0 + x1y1 - (x1-x0)*(y1-y0))<<B */ if (mp_lshd (&x1y1, B * 2) != MP_OKAY) goto X1Y1; /* x1y1 = x1y1 << 2*B */ if (mp_add (&x0y0, &t1, &t1) != MP_OKAY) goto X1Y1; /* t1 = x0y0 + t1 */ if (mp_add (&t1, &x1y1, c) != MP_OKAY) goto X1Y1; /* t1 = x0y0 + t1 + x1y1 */ /* Algorithm succeeded set the return code to MP_OKAY */ err = MP_OKAY; X1Y1:mp_clear (&x1y1); X0Y0:mp_clear (&x0y0); T1:mp_clear (&t1); Y1:mp_clear (&y1); Y0:mp_clear (&y0); X1:mp_clear (&x1); X0:mp_clear (&x0); ERR: return err; }
int main(int argc, char *argv[]) { mp_int a, b, c; int pco; mp_err res; printf("Test 9: Logical functions\n\n"); if(argc < 3) { fprintf(stderr, "Usage: %s <a> <b>\n", argv[0]); return 1; } mp_init(&a); mp_init(&b); mp_init(&c); mp_read_radix(&a, argv[1], 16); mp_read_radix(&b, argv[2], 16); printf("a = "); mp_print(&a, stdout); fputc('\n', stdout); printf("b = "); mp_print(&b, stdout); fputc('\n', stdout); mpl_not(&a, &c); printf("~a = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_and(&a, &b, &c); printf("a & b = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_or(&a, &b, &c); printf("a | b = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_xor(&a, &b, &c); printf("a ^ b = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_rsh(&a, &c, 1); printf("a >> 1 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_rsh(&a, &c, 5); printf("a >> 5 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_rsh(&a, &c, 16); printf("a >> 16 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_lsh(&a, &c, 1); printf("a << 1 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_lsh(&a, &c, 5); printf("a << 5 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_lsh(&a, &c, 16); printf("a << 16 = "); mp_print(&c, stdout); fputc('\n', stdout); mpl_num_set(&a, &pco); printf("population(a) = %d\n", pco); mpl_num_set(&b, &pco); printf("population(b) = %d\n", pco); res = mpl_parity(&a); if(res == MP_EVEN) printf("a has even parity\n"); else printf("a has odd parity\n"); mp_clear(&c); mp_clear(&b); mp_clear(&a); return 0; }
int ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_set_type *dp) { int err; ecc_point *base; void *prime; unsigned char *buf; int keysize; LTC_ARGCHK(key != NULL); LTC_ARGCHK(ltc_mp.name != NULL); LTC_ARGCHK(dp != NULL); /* good prng? */ if ((err = prng_is_valid(wprng)) != CRYPT_OK) { return err; } key->idx = -1; key->dp = dp; keysize = dp->size; /* allocate ram */ base = NULL; buf = XMALLOC(ECC_MAXSIZE); if (buf == NULL) { return CRYPT_MEM; } /* make up random string */ if (prng_descriptor[wprng].read(buf, (unsigned long)keysize, prng) != (unsigned long)keysize) { err = CRYPT_ERROR_READPRNG; goto ERR_BUF; } /* setup the key variables */ if ((err = mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k, &prime, NULL)) != CRYPT_OK) { goto ERR_BUF; } base = ltc_ecc_new_point(); if (base == NULL) { err = CRYPT_MEM; goto errkey; } /* read in the specs for this key */ if ((err = mp_read_radix(prime, (char *)key->dp->prime, 16)) != CRYPT_OK) { goto errkey; } if ((err = mp_read_radix(base->x, (char *)key->dp->Gx, 16)) != CRYPT_OK) { goto errkey; } if ((err = mp_read_radix(base->y, (char *)key->dp->Gy, 16)) != CRYPT_OK) { goto errkey; } if ((err = mp_set(base->z, 1)) != CRYPT_OK) { goto errkey; } if ((err = mp_read_unsigned_bin(key->k, (unsigned char *)buf, keysize)) != CRYPT_OK) { goto errkey; } /* make the public key */ if ((err = ltc_mp.ecc_ptmul(key->k, base, &key->pubkey, prime, 1)) != CRYPT_OK) { goto errkey; } key->type = PK_PRIVATE; /* free up ram */ err = CRYPT_OK; goto cleanup; errkey: mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL); cleanup: ltc_ecc_del_point(base); mp_clear(prime); ERR_BUF: #ifdef LTC_CLEAN_STACK zeromem(buf, ECC_MAXSIZE); #endif XFREE(buf); return err; }
/* reduces x mod m, assumes 0 < x < m**2, mu is * precomputed via mp_reduce_setup. * From HAC pp.604 Algorithm 14.42 */ int mp_reduce (mp_int * x, mp_int * m, mp_int * mu) { mp_int q; int res, um = m->used; /* q = x */ if ((res = mp_init_copy (&q, x)) != MP_OKAY) { return res; } /* q1 = x / b**(k-1) */ mp_rshd (&q, um - 1); /* according to HAC this optimization is ok */ if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) { if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) { goto CLEANUP; } } else { #ifdef BN_S_MP_MUL_HIGH_DIGS_C if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) { goto CLEANUP; } #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C) if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) { goto CLEANUP; } #else { res = MP_VAL; goto CLEANUP; } #endif } /* q3 = q2 / b**(k+1) */ mp_rshd (&q, um + 1); /* x = x mod b**(k+1), quick (no division) */ if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) { goto CLEANUP; } /* q = q * m mod b**(k+1), quick (no division) */ if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) { goto CLEANUP; } /* x = x - q */ if ((res = mp_sub (x, &q, x)) != MP_OKAY) { goto CLEANUP; } /* If x < 0, add b**(k+1) to it */ if (mp_cmp_d (x, 0) == MP_LT) { mp_set (&q, 1); if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) goto CLEANUP; if ((res = mp_add (x, &q, x)) != MP_OKAY) goto CLEANUP; } /* Back off if it's too big */ while (mp_cmp (x, m) != MP_LT) { if ((res = s_mp_sub (x, m, x)) != MP_OKAY) { goto CLEANUP; } } CLEANUP: mp_clear (&q); return res; }
/* 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 }
int main(void) { mp_int a, b, c, d, e, f; unsigned long expt_n, add_n, sub_n, mul_n, div_n, sqr_n, mul2d_n, div2d_n, gcd_n, lcm_n, inv_n, div2_n, mul2_n, add_d_n, sub_d_n, t; unsigned rr; int i, n, err, cnt, ix, old_kara_m, old_kara_s; mp_init(&a); mp_init(&b); mp_init(&c); mp_init(&d); mp_init(&e); mp_init(&f); srand(time(NULL)); #if 0 // test mp_get_int printf("Testing: mp_get_int\n"); for(i=0;i<1000;++i) { t = ((unsigned long)rand()*rand()+1)&0xFFFFFFFF; mp_set_int(&a,t); if (t!=mp_get_int(&a)) { printf("mp_get_int() bad result!\n"); return 1; } } mp_set_int(&a,0); if (mp_get_int(&a)!=0) { printf("mp_get_int() bad result!\n"); return 1; } mp_set_int(&a,0xffffffff); if (mp_get_int(&a)!=0xffffffff) { printf("mp_get_int() bad result!\n"); return 1; } // test mp_sqrt printf("Testing: mp_sqrt\n"); for (i=0;i<1000;++i) { printf("%6d\r", i); fflush(stdout); n = (rand()&15)+1; mp_rand(&a,n); if (mp_sqrt(&a,&b) != MP_OKAY) { printf("mp_sqrt() error!\n"); return 1; } mp_n_root(&a,2,&a); if (mp_cmp_mag(&b,&a) != MP_EQ) { printf("mp_sqrt() bad result!\n"); return 1; } } printf("\nTesting: mp_is_square\n"); for (i=0;i<1000;++i) { printf("%6d\r", i); fflush(stdout); /* test mp_is_square false negatives */ n = (rand()&7)+1; mp_rand(&a,n); mp_sqr(&a,&a); if (mp_is_square(&a,&n)!=MP_OKAY) { printf("fn:mp_is_square() error!\n"); return 1; } if (n==0) { printf("fn:mp_is_square() bad result!\n"); return 1; } /* test for false positives */ mp_add_d(&a, 1, &a); if (mp_is_square(&a,&n)!=MP_OKAY) { printf("fp:mp_is_square() error!\n"); return 1; } if (n==1) { printf("fp:mp_is_square() bad result!\n"); return 1; } } printf("\n\n"); /* test for size */ for (ix = 10; ix < 256; ix++) { printf("Testing (not safe-prime): %9d bits \r", ix); fflush(stdout); err = mp_prime_random_ex(&a, 8, ix, (rand()&1)?LTM_PRIME_2MSB_OFF:LTM_PRIME_2MSB_ON, myrng, NULL); if (err != MP_OKAY) { printf("failed with err code %d\n", err); return EXIT_FAILURE; } if (mp_count_bits(&a) != ix) { printf("Prime is %d not %d bits!!!\n", mp_count_bits(&a), ix); return EXIT_FAILURE; } } for (ix = 16; ix < 256; ix++) { printf("Testing ( safe-prime): %9d bits \r", ix); fflush(stdout); err = mp_prime_random_ex(&a, 8, ix, ((rand()&1)?LTM_PRIME_2MSB_OFF:LTM_PRIME_2MSB_ON)|LTM_PRIME_SAFE, myrng, NULL); if (err != MP_OKAY) { printf("failed with err code %d\n", err); return EXIT_FAILURE; } if (mp_count_bits(&a) != ix) { printf("Prime is %d not %d bits!!!\n", mp_count_bits(&a), ix); return EXIT_FAILURE; } /* let's see if it's really a safe prime */ mp_sub_d(&a, 1, &a); mp_div_2(&a, &a); mp_prime_is_prime(&a, 8, &cnt); if (cnt != MP_YES) { printf("sub is not prime!\n"); return EXIT_FAILURE; } } printf("\n\n"); mp_read_radix(&a, "123456", 10); mp_toradix_n(&a, buf, 10, 3); printf("a == %s\n", buf); mp_toradix_n(&a, buf, 10, 4); printf("a == %s\n", buf); mp_toradix_n(&a, buf, 10, 30); printf("a == %s\n", buf); #if 0 for (;;) { fgets(buf, sizeof(buf), stdin); mp_read_radix(&a, buf, 10); mp_prime_next_prime(&a, 5, 1); mp_toradix(&a, buf, 10); printf("%s, %lu\n", buf, a.dp[0] & 3); } #endif /* test mp_cnt_lsb */ printf("testing mp_cnt_lsb...\n"); mp_set(&a, 1); for (ix = 0; ix < 1024; ix++) { if (mp_cnt_lsb(&a) != ix) { printf("Failed at %d, %d\n", ix, mp_cnt_lsb(&a)); return 0; } mp_mul_2(&a, &a); } /* test mp_reduce_2k */ printf("Testing mp_reduce_2k...\n"); for (cnt = 3; cnt <= 128; ++cnt) { mp_digit tmp; mp_2expt(&a, cnt); mp_sub_d(&a, 2, &a); /* a = 2**cnt - 2 */ printf("\nTesting %4d bits", cnt); printf("(%d)", mp_reduce_is_2k(&a)); mp_reduce_2k_setup(&a, &tmp); printf("(%d)", tmp); for (ix = 0; ix < 1000; ix++) { if (!(ix & 127)) {printf("."); fflush(stdout); } mp_rand(&b, (cnt/DIGIT_BIT + 1) * 2); mp_copy(&c, &b); mp_mod(&c, &a, &c); mp_reduce_2k(&b, &a, 1); if (mp_cmp(&c, &b)) { printf("FAILED\n"); exit(0); } } } /* test mp_div_3 */ printf("Testing mp_div_3...\n"); mp_set(&d, 3); for (cnt = 0; cnt < 10000; ) { mp_digit r1, r2; if (!(++cnt & 127)) printf("%9d\r", cnt); mp_rand(&a, abs(rand()) % 128 + 1); mp_div(&a, &d, &b, &e); mp_div_3(&a, &c, &r2); if (mp_cmp(&b, &c) || mp_cmp_d(&e, r2)) { printf("\n\nmp_div_3 => Failure\n"); } } printf("\n\nPassed div_3 testing\n"); /* test the DR reduction */ printf("testing mp_dr_reduce...\n"); for (cnt = 2; cnt < 32; cnt++) { printf("%d digit modulus\n", cnt); mp_grow(&a, cnt); mp_zero(&a); for (ix = 1; ix < cnt; ix++) { a.dp[ix] = MP_MASK; } a.used = cnt; a.dp[0] = 3; mp_rand(&b, cnt - 1); mp_copy(&b, &c); rr = 0; do { if (!(rr & 127)) { printf("%9lu\r", rr); fflush(stdout); } mp_sqr(&b, &b); mp_add_d(&b, 1, &b); mp_copy(&b, &c); mp_mod(&b, &a, &b); mp_dr_reduce(&c, &a, (((mp_digit)1)<<DIGIT_BIT)-a.dp[0]); if (mp_cmp(&b, &c) != MP_EQ) { printf("Failed on trial %lu\n", rr); exit(-1); } } while (++rr < 500); printf("Passed DR test for %d digits\n", cnt); } #endif div2_n = mul2_n = inv_n = expt_n = lcm_n = gcd_n = add_n = sub_n = mul_n = div_n = sqr_n = mul2d_n = div2d_n = cnt = add_d_n = sub_d_n= 0; /* force KARA and TOOM to enable despite cutoffs */ KARATSUBA_SQR_CUTOFF = KARATSUBA_MUL_CUTOFF = 110; TOOM_SQR_CUTOFF = TOOM_MUL_CUTOFF = 150; for (;;) { /* randomly clear and re-init one variable, this has the affect of triming the alloc space */ switch (abs(rand()) % 7) { case 0: mp_clear(&a); mp_init(&a); break; case 1: mp_clear(&b); mp_init(&b); break; case 2: mp_clear(&c); mp_init(&c); break; case 3: mp_clear(&d); mp_init(&d); break; case 4: mp_clear(&e); mp_init(&e); break; case 5: mp_clear(&f); mp_init(&f); break; case 6: break; /* don't clear any */ } printf("%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu/%4lu ", add_n, sub_n, mul_n, div_n, sqr_n, mul2d_n, div2d_n, gcd_n, lcm_n, expt_n, inv_n, div2_n, mul2_n, add_d_n, sub_d_n); fgets(cmd, 4095, stdin); cmd[strlen(cmd)-1] = 0; printf("%s ]\r",cmd); fflush(stdout); if (!strcmp(cmd, "mul2d")) { ++mul2d_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); sscanf(buf, "%d", &rr); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_mul_2d(&a, rr, &a); a.sign = b.sign; if (mp_cmp(&a, &b) != MP_EQ) { printf("mul2d failed, rr == %d\n",rr); draw(&a); draw(&b); return 0; } } else if (!strcmp(cmd, "div2d")) { ++div2d_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); sscanf(buf, "%d", &rr); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_div_2d(&a, rr, &a, &e); a.sign = b.sign; if (a.used == b.used && a.used == 0) { a.sign = b.sign = MP_ZPOS; } if (mp_cmp(&a, &b) != MP_EQ) { printf("div2d failed, rr == %d\n",rr); draw(&a); draw(&b); return 0; } } else if (!strcmp(cmd, "add")) { ++add_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_copy(&a, &d); mp_add(&d, &b, &d); if (mp_cmp(&c, &d) != MP_EQ) { printf("add %lu failure!\n", add_n); draw(&a);draw(&b);draw(&c);draw(&d); return 0; } /* test the sign/unsigned storage functions */ rr = mp_signed_bin_size(&c); mp_to_signed_bin(&c, (unsigned char *)cmd); memset(cmd+rr, rand()&255, sizeof(cmd)-rr); mp_read_signed_bin(&d, (unsigned char *)cmd, rr); if (mp_cmp(&c, &d) != MP_EQ) { printf("mp_signed_bin failure!\n"); draw(&c); draw(&d); return 0; } rr = mp_unsigned_bin_size(&c); mp_to_unsigned_bin(&c, (unsigned char *)cmd); memset(cmd+rr, rand()&255, sizeof(cmd)-rr); mp_read_unsigned_bin(&d, (unsigned char *)cmd, rr); if (mp_cmp_mag(&c, &d) != MP_EQ) { printf("mp_unsigned_bin failure!\n"); draw(&c); draw(&d); return 0; } } else if (!strcmp(cmd, "sub")) { ++sub_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_copy(&a, &d); mp_sub(&d, &b, &d); if (mp_cmp(&c, &d) != MP_EQ) { printf("sub %lu failure!\n", sub_n); draw(&a);draw(&b);draw(&c);draw(&d); return 0; } } else if (!strcmp(cmd, "mul")) { ++mul_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_copy(&a, &d); mp_mul(&d, &b, &d); if (mp_cmp(&c, &d) != MP_EQ) { printf("mul %lu failure!\n", mul_n); draw(&a);draw(&b);draw(&c);draw(&d); return 0; } } else if (!strcmp(cmd, "div")) { ++div_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&d, buf, 64); mp_div(&a, &b, &e, &f); if (mp_cmp(&c, &e) != MP_EQ || mp_cmp(&d, &f) != MP_EQ) { printf("div %lu %d, %d, failure!\n", div_n, mp_cmp(&c, &e), mp_cmp(&d, &f)); draw(&a);draw(&b);draw(&c);draw(&d); draw(&e); draw(&f); return 0; } } else if (!strcmp(cmd, "sqr")) { ++sqr_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_copy(&a, &c); mp_sqr(&c, &c); if (mp_cmp(&b, &c) != MP_EQ) { printf("sqr %lu failure!\n", sqr_n); draw(&a);draw(&b);draw(&c); return 0; } } else if (!strcmp(cmd, "gcd")) { ++gcd_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_copy(&a, &d); mp_gcd(&d, &b, &d); d.sign = c.sign; if (mp_cmp(&c, &d) != MP_EQ) { printf("gcd %lu failure!\n", gcd_n); draw(&a);draw(&b);draw(&c);draw(&d); return 0; } } else if (!strcmp(cmd, "lcm")) { ++lcm_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_copy(&a, &d); mp_lcm(&d, &b, &d); d.sign = c.sign; if (mp_cmp(&c, &d) != MP_EQ) { printf("lcm %lu failure!\n", lcm_n); draw(&a);draw(&b);draw(&c);draw(&d); return 0; } } else if (!strcmp(cmd, "expt")) { ++expt_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&d, buf, 64); mp_copy(&a, &e); mp_exptmod(&e, &b, &c, &e); if (mp_cmp(&d, &e) != MP_EQ) { printf("expt %lu failure!\n", expt_n); draw(&a);draw(&b);draw(&c);draw(&d); draw(&e); return 0; } } else if (!strcmp(cmd, "invmod")) { ++inv_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&c, buf, 64); mp_invmod(&a, &b, &d); mp_mulmod(&d,&a,&b,&e); if (mp_cmp_d(&e, 1) != MP_EQ) { printf("inv [wrong value from MPI?!] failure\n"); draw(&a);draw(&b);draw(&c);draw(&d); mp_gcd(&a, &b, &e); draw(&e); return 0; } } else if (!strcmp(cmd, "div2")) { ++div2_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_div_2(&a, &c); if (mp_cmp(&c, &b) != MP_EQ) { printf("div_2 %lu failure\n", div2_n); draw(&a); draw(&b); draw(&c); return 0; } } else if (!strcmp(cmd, "mul2")) { ++mul2_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_mul_2(&a, &c); if (mp_cmp(&c, &b) != MP_EQ) { printf("mul_2 %lu failure\n", mul2_n); draw(&a); draw(&b); draw(&c); return 0; } } else if (!strcmp(cmd, "add_d")) { ++add_d_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); sscanf(buf, "%d", &ix); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_add_d(&a, ix, &c); if (mp_cmp(&b, &c) != MP_EQ) { printf("add_d %lu failure\n", add_d_n); draw(&a); draw(&b); draw(&c); printf("d == %d\n", ix); return 0; } } else if (!strcmp(cmd, "sub_d")) { ++sub_d_n; fgets(buf, 4095, stdin); mp_read_radix(&a, buf, 64); fgets(buf, 4095, stdin); sscanf(buf, "%d", &ix); fgets(buf, 4095, stdin); mp_read_radix(&b, buf, 64); mp_sub_d(&a, ix, &c); if (mp_cmp(&b, &c) != MP_EQ) { printf("sub_d %lu failure\n", sub_d_n); draw(&a); draw(&b); draw(&c); printf("d == %d\n", ix); return 0; } } } return 0; }
/* ** Checks the signature on the given digest using the key provided. */ SECStatus ECDSA_VerifyDigest(ECPublicKey *key, const SECItem *signature, const SECItem *digest) { SECStatus rv = SECFailure; #ifdef NSS_ENABLE_ECC mp_int r_, s_; /* tuple (r', s') is received signature) */ mp_int c, u1, u2, v; /* intermediate values used in verification */ mp_int x1; mp_int n; mp_err err = MP_OKAY; ECParams *ecParams = NULL; SECItem pointC = { siBuffer, NULL, 0 }; int slen; /* length in bytes of a half signature (r or s) */ int flen; /* length in bytes of the field size */ unsigned olen; /* length in bytes of the base point order */ unsigned obits; /* length in bits of the base point order */ #if EC_DEBUG char mpstr[256]; printf("ECDSA verification called\n"); #endif /* Initialize MPI integers. */ /* must happen before the first potential call to cleanup */ MP_DIGITS(&r_) = 0; MP_DIGITS(&s_) = 0; MP_DIGITS(&c) = 0; MP_DIGITS(&u1) = 0; MP_DIGITS(&u2) = 0; MP_DIGITS(&x1) = 0; MP_DIGITS(&v) = 0; MP_DIGITS(&n) = 0; /* Check args */ if (!key || !signature || !digest) { PORT_SetError(SEC_ERROR_INVALID_ARGS); goto cleanup; } ecParams = &(key->ecParams); flen = (ecParams->fieldID.size + 7) >> 3; olen = ecParams->order.len; if (signature->len == 0 || signature->len%2 != 0 || signature->len > 2*olen) { PORT_SetError(SEC_ERROR_INPUT_LEN); goto cleanup; } slen = signature->len/2; SECITEM_AllocItem(NULL, &pointC, 2*flen + 1); if (pointC.data == NULL) goto cleanup; CHECK_MPI_OK( mp_init(&r_) ); CHECK_MPI_OK( mp_init(&s_) ); CHECK_MPI_OK( mp_init(&c) ); CHECK_MPI_OK( mp_init(&u1) ); CHECK_MPI_OK( mp_init(&u2) ); CHECK_MPI_OK( mp_init(&x1) ); CHECK_MPI_OK( mp_init(&v) ); CHECK_MPI_OK( mp_init(&n) ); /* ** Convert received signature (r', s') into MPI integers. */ CHECK_MPI_OK( mp_read_unsigned_octets(&r_, signature->data, slen) ); CHECK_MPI_OK( mp_read_unsigned_octets(&s_, signature->data + slen, slen) ); /* ** ANSI X9.62, Section 5.4.2, Steps 1 and 2 ** ** Verify that 0 < r' < n and 0 < s' < n */ SECITEM_TO_MPINT(ecParams->order, &n); if (mp_cmp_z(&r_) <= 0 || mp_cmp_z(&s_) <= 0 || mp_cmp(&r_, &n) >= 0 || mp_cmp(&s_, &n) >= 0) { PORT_SetError(SEC_ERROR_BAD_SIGNATURE); goto cleanup; /* will return rv == SECFailure */ } /* ** ANSI X9.62, Section 5.4.2, Step 3 ** ** c = (s')**-1 mod n */ CHECK_MPI_OK( mp_invmod(&s_, &n, &c) ); /* c = (s')**-1 mod n */ /* ** ANSI X9.62, Section 5.4.2, Step 4 ** ** u1 = ((HASH(M')) * c) mod n */ SECITEM_TO_MPINT(*digest, &u1); /* u1 = HASH(M) */ /* In the definition of EC signing, digests are truncated * to the length of n in bits. * (see SEC 1 "Elliptic Curve Digit Signature Algorithm" section 4.1.*/ CHECK_MPI_OK( (obits = mpl_significant_bits(&n)) ); if (digest->len*8 > obits) { /* u1 = HASH(M') */ mpl_rsh(&u1,&u1,digest->len*8 - obits); } #if EC_DEBUG mp_todecimal(&r_, mpstr); printf("r_: %s (dec)\n", mpstr); mp_todecimal(&s_, mpstr); printf("s_: %s (dec)\n", mpstr); mp_todecimal(&c, mpstr); printf("c : %s (dec)\n", mpstr); mp_todecimal(&u1, mpstr); printf("digest: %s (dec)\n", mpstr); #endif CHECK_MPI_OK( mp_mulmod(&u1, &c, &n, &u1) ); /* u1 = u1 * c mod n */ /* ** ANSI X9.62, Section 5.4.2, Step 4 ** ** u2 = ((r') * c) mod n */ CHECK_MPI_OK( mp_mulmod(&r_, &c, &n, &u2) ); /* ** ANSI X9.62, Section 5.4.3, Step 1 ** ** Compute u1*G + u2*Q ** Here, A = u1.G B = u2.Q and C = A + B ** If the result, C, is the point at infinity, reject the signature */ if (ec_points_mul(ecParams, &u1, &u2, &key->publicValue, &pointC) != SECSuccess) { rv = SECFailure; goto cleanup; } if (ec_point_at_infinity(&pointC)) { PORT_SetError(SEC_ERROR_BAD_SIGNATURE); rv = SECFailure; goto cleanup; } CHECK_MPI_OK( mp_read_unsigned_octets(&x1, pointC.data + 1, flen) ); /* ** ANSI X9.62, Section 5.4.4, Step 2 ** ** v = x1 mod n */ CHECK_MPI_OK( mp_mod(&x1, &n, &v) ); #if EC_DEBUG mp_todecimal(&r_, mpstr); printf("r_: %s (dec)\n", mpstr); mp_todecimal(&v, mpstr); printf("v : %s (dec)\n", mpstr); #endif /* ** ANSI X9.62, Section 5.4.4, Step 3 ** ** Verification: v == r' */ if (mp_cmp(&v, &r_)) { PORT_SetError(SEC_ERROR_BAD_SIGNATURE); rv = SECFailure; /* Signature failed to verify. */ } else { rv = SECSuccess; /* Signature verified. */ } #if EC_DEBUG mp_todecimal(&u1, mpstr); printf("u1: %s (dec)\n", mpstr); mp_todecimal(&u2, mpstr); printf("u2: %s (dec)\n", mpstr); mp_tohex(&x1, mpstr); printf("x1: %s\n", mpstr); mp_todecimal(&v, mpstr); printf("v : %s (dec)\n", mpstr); #endif cleanup: mp_clear(&r_); mp_clear(&s_); mp_clear(&c); mp_clear(&u1); mp_clear(&u2); mp_clear(&x1); mp_clear(&v); mp_clear(&n); if (pointC.data) SECITEM_FreeItem(&pointC, PR_FALSE); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } #if EC_DEBUG printf("ECDSA verification %s\n", (rv == SECSuccess) ? "succeeded" : "failed"); #endif #else PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); #endif /* NSS_ENABLE_ECC */ return rv; }
/* * Computes scalar point multiplication pointQ = k1 * G + k2 * pointP for * the curve whose parameters are encoded in params with base point G. */ SECStatus ec_points_mul(const ECParams *params, const mp_int *k1, const mp_int *k2, const SECItem *pointP, SECItem *pointQ) { mp_int Px, Py, Qx, Qy; mp_int Gx, Gy, order, irreducible, a, b; #if 0 /* currently don't support non-named curves */ unsigned int irr_arr[5]; #endif ECGroup *group = NULL; SECStatus rv = SECFailure; mp_err err = MP_OKAY; int len; #if EC_DEBUG int i; char mpstr[256]; printf("ec_points_mul: params [len=%d]:", params->DEREncoding.len); for (i = 0; i < params->DEREncoding.len; i++) printf("%02x:", params->DEREncoding.data[i]); printf("\n"); if (k1 != NULL) { mp_tohex(k1, mpstr); printf("ec_points_mul: scalar k1: %s\n", mpstr); mp_todecimal(k1, mpstr); printf("ec_points_mul: scalar k1: %s (dec)\n", mpstr); } if (k2 != NULL) { mp_tohex(k2, mpstr); printf("ec_points_mul: scalar k2: %s\n", mpstr); mp_todecimal(k2, mpstr); printf("ec_points_mul: scalar k2: %s (dec)\n", mpstr); } if (pointP != NULL) { printf("ec_points_mul: pointP [len=%d]:", pointP->len); for (i = 0; i < pointP->len; i++) printf("%02x:", pointP->data[i]); printf("\n"); } #endif /* NOTE: We only support uncompressed points for now */ len = (params->fieldID.size + 7) >> 3; if (pointP != NULL) { if ((pointP->data[0] != EC_POINT_FORM_UNCOMPRESSED) || (pointP->len != (2 * len + 1))) { PORT_SetError(SEC_ERROR_UNSUPPORTED_EC_POINT_FORM); return SECFailure; }; } MP_DIGITS(&Px) = 0; MP_DIGITS(&Py) = 0; MP_DIGITS(&Qx) = 0; MP_DIGITS(&Qy) = 0; MP_DIGITS(&Gx) = 0; MP_DIGITS(&Gy) = 0; MP_DIGITS(&order) = 0; MP_DIGITS(&irreducible) = 0; MP_DIGITS(&a) = 0; MP_DIGITS(&b) = 0; CHECK_MPI_OK( mp_init(&Px) ); CHECK_MPI_OK( mp_init(&Py) ); CHECK_MPI_OK( mp_init(&Qx) ); CHECK_MPI_OK( mp_init(&Qy) ); CHECK_MPI_OK( mp_init(&Gx) ); CHECK_MPI_OK( mp_init(&Gy) ); CHECK_MPI_OK( mp_init(&order) ); CHECK_MPI_OK( mp_init(&irreducible) ); CHECK_MPI_OK( mp_init(&a) ); CHECK_MPI_OK( mp_init(&b) ); if ((k2 != NULL) && (pointP != NULL)) { /* Initialize Px and Py */ CHECK_MPI_OK( mp_read_unsigned_octets(&Px, pointP->data + 1, (mp_size) len) ); CHECK_MPI_OK( mp_read_unsigned_octets(&Py, pointP->data + 1 + len, (mp_size) len) ); } /* construct from named params, if possible */ if (params->name != ECCurve_noName) { group = ECGroup_fromName(params->name); } #if 0 /* currently don't support non-named curves */ if (group == NULL) { /* Set up mp_ints containing the curve coefficients */ CHECK_MPI_OK( mp_read_unsigned_octets(&Gx, params->base.data + 1, (mp_size) len) ); CHECK_MPI_OK( mp_read_unsigned_octets(&Gy, params->base.data + 1 + len, (mp_size) len) ); SECITEM_TO_MPINT( params->order, &order ); SECITEM_TO_MPINT( params->curve.a, &a ); SECITEM_TO_MPINT( params->curve.b, &b ); if (params->fieldID.type == ec_field_GFp) { SECITEM_TO_MPINT( params->fieldID.u.prime, &irreducible ); group = ECGroup_consGFp(&irreducible, &a, &b, &Gx, &Gy, &order, params->cofactor); } else { SECITEM_TO_MPINT( params->fieldID.u.poly, &irreducible ); irr_arr[0] = params->fieldID.size; irr_arr[1] = params->fieldID.k1; irr_arr[2] = params->fieldID.k2; irr_arr[3] = params->fieldID.k3; irr_arr[4] = 0; group = ECGroup_consGF2m(&irreducible, irr_arr, &a, &b, &Gx, &Gy, &order, params->cofactor); } } #endif if (group == NULL) goto cleanup; if ((k2 != NULL) && (pointP != NULL)) { CHECK_MPI_OK( ECPoints_mul(group, k1, k2, &Px, &Py, &Qx, &Qy) ); } else { CHECK_MPI_OK( ECPoints_mul(group, k1, NULL, NULL, NULL, &Qx, &Qy) ); } /* Construct the SECItem representation of point Q */ pointQ->data[0] = EC_POINT_FORM_UNCOMPRESSED; CHECK_MPI_OK( mp_to_fixlen_octets(&Qx, pointQ->data + 1, (mp_size) len) ); CHECK_MPI_OK( mp_to_fixlen_octets(&Qy, pointQ->data + 1 + len, (mp_size) len) ); rv = SECSuccess; #if EC_DEBUG printf("ec_points_mul: pointQ [len=%d]:", pointQ->len); for (i = 0; i < pointQ->len; i++) printf("%02x:", pointQ->data[i]); printf("\n"); #endif cleanup: ECGroup_free(group); mp_clear(&Px); mp_clear(&Py); mp_clear(&Qx); mp_clear(&Qy); mp_clear(&Gx); mp_clear(&Gy); mp_clear(&order); mp_clear(&irreducible); mp_clear(&a); mp_clear(&b); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; }
/* ** 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; }
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; }
/** 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; }
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; }
/** * bignum_deinit - Free bignum * @n: Bignum from bignum_init() */ void bignum_deinit(struct bignum *n) { if (n) { mp_clear((mp_int *) n); os_free(n); } }
/* single digit division (based on routine from MPI) */ int mp_div_d (mp_int * a, mp_digit b, mp_int * c, mp_digit * d) { mp_int q; mp_word w; mp_digit t; int res, ix; /* cannot divide by zero */ if (b == 0) { return MP_VAL; } /* quick outs */ if (b == 1 || mp_iszero(a) == 1) { if (d != NULL) { *d = 0; } if (c != NULL) { return mp_copy(a, c); } return MP_OKAY; } /* power of two ? */ if (s_is_power_of_two(b, &ix) == 1) { if (d != NULL) { *d = a->dp[0] & ((((mp_digit)1)<<ix) - 1); } if (c != NULL) { return mp_div_2d(a, ix, c, NULL); } return MP_OKAY; } #ifdef BN_MP_DIV_3_C /* three? */ if (b == 3) { return mp_div_3(a, c, d); } #endif /* no easy answer [c'est la vie]. Just division */ if ((res = mp_init_size(&q, a->used)) != MP_OKAY) { return res; } q.used = a->used; q.sign = a->sign; w = 0; for (ix = a->used - 1; ix >= 0; ix--) { w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); if (w >= b) { t = (mp_digit)(w / b); w -= ((mp_word)t) * ((mp_word)b); } else { t = 0; } q.dp[ix] = (mp_digit)t; } if (d != NULL) { *d = (mp_digit)w; } if (c != NULL) { mp_clamp(&q); mp_exch(&q, c); } mp_clear(&q); return res; }
/* find the n'th root of an integer * * Result found such that (c)**b <= a and (c+1)**b > a * * This algorithm uses Newton's approximation * x[i+1] = x[i] - f(x[i])/f'(x[i]) * which will find the root in log(N) time where * each step involves a fair bit. This is not meant to * find huge roots [square and cube, etc]. */ int mp_n_root (mp_int * a, mp_digit b, mp_int * c) { mp_int t1, t2, t3; int res, neg; /* input must be positive if b is even */ if ((b & 1) == 0 && a->sign == MP_NEG) { return MP_VAL; } if ((res = mp_init (&t1)) != MP_OKAY) { return res; } if ((res = mp_init (&t2)) != MP_OKAY) { goto __T1; } if ((res = mp_init (&t3)) != MP_OKAY) { goto __T2; } /* if a is negative fudge the sign but keep track */ neg = a->sign; a->sign = MP_ZPOS; /* t2 = 2 */ mp_set (&t2, 2); do { /* t1 = t2 */ if ((res = mp_copy (&t2, &t1)) != MP_OKAY) { goto __T3; } /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */ /* t3 = t1**(b-1) */ if ((res = mp_expt_d (&t1, b - 1, &t3)) != MP_OKAY) { goto __T3; } /* numerator */ /* t2 = t1**b */ if ((res = mp_mul (&t3, &t1, &t2)) != MP_OKAY) { goto __T3; } /* t2 = t1**b - a */ if ((res = mp_sub (&t2, a, &t2)) != MP_OKAY) { goto __T3; } /* denominator */ /* t3 = t1**(b-1) * b */ if ((res = mp_mul_d (&t3, b, &t3)) != MP_OKAY) { goto __T3; } /* t3 = (t1**b - a)/(b * t1**(b-1)) */ if ((res = mp_div (&t2, &t3, &t3, NULL)) != MP_OKAY) { goto __T3; } if ((res = mp_sub (&t1, &t3, &t2)) != MP_OKAY) { goto __T3; } } while (mp_cmp (&t1, &t2) != MP_EQ); /* result can be off by a few so check */ for (;;) { if ((res = mp_expt_d (&t1, b, &t2)) != MP_OKAY) { goto __T3; } if (mp_cmp (&t2, a) == MP_GT) { if ((res = mp_sub_d (&t1, 1, &t1)) != MP_OKAY) { goto __T3; } } else { break; } } /* reset the sign of a first */ a->sign = neg; /* set the result */ mp_exch (&t1, c); /* set the sign of the result */ c->sign = neg; res = MP_OKAY; __T3:mp_clear (&t3); __T2:mp_clear (&t2); __T1:mp_clear (&t1); return res; }
SECStatus RSA_PrivateKeyCheck(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) ); 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) { /* mind the p's and q's (and d_p's and d_q's) */ SECItem tmp; mp_exch(&p, &q); mp_exch(&d_p,&d_q); tmp = key->prime1; key->prime1 = key->prime2; key->prime2 = tmp; tmp = key->exponent1; key->exponent1 = key->exponent2; key->exponent2 = tmp; } #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. */ /* d_p == d mod p-1 */ CHECK_MPI_OK( mp_mod(&d, &psub1, &res) ); if (mp_cmp(&d_p, &res) != 0) { /* swap in the correct value */ CHECK_SEC_OK( swap_in_key_value(key->arena, &res, &key->exponent1) ); } /* d_q == d mod q-1 */ CHECK_MPI_OK( mp_mod(&d, &qsub1, &res) ); if (mp_cmp(&d_q, &res) != 0) { /* swap in the correct value */ CHECK_SEC_OK( swap_in_key_value(key->arena, &res, &key->exponent2) ); } /* q * q**-1 == 1 mod p */ CHECK_MPI_OK( mp_mulmod(&q, &qInv, &p, &res) ); if (mp_cmp_d(&res, 1) != 0) { /* compute the correct value */ CHECK_MPI_OK( mp_invmod(&q, &p, &qInv) ); CHECK_SEC_OK( swap_in_key_value(key->arena, &qInv, &key->coefficient) ); } 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; }
/* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */ int s_mp_sqr (mp_int * a, mp_int * b) { mp_int t; int res, ix, iy, pa; mp_word r; mp_digit u, tmpx, *tmpt; pa = a->used; if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) { return res; } /* default used is maximum possible size */ t.used = 2*pa + 1; for (ix = 0; ix < pa; ix++) { /* first calculate the digit at 2*ix */ /* calculate double precision result */ r = ((mp_word) t.dp[2*ix]) + ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]); /* store lower part in result */ t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK)); /* get the carry */ u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); /* left hand side of A[ix] * A[iy] */ tmpx = a->dp[ix]; /* alias for where to store the results */ tmpt = t.dp + (2*ix + 1); for (iy = ix + 1; iy < pa; iy++) { /* first calculate the product */ r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]); /* now calculate the double precision result, note we use * addition instead of *2 since it's easier to optimize */ r = ((mp_word) *tmpt) + r + r + ((mp_word) u); /* store lower part */ *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* get carry */ u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); } /* propagate upwards */ while (u != ((mp_digit) 0)) { r = ((mp_word) *tmpt) + ((mp_word) u); *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); } } mp_clamp (&t); mp_exch (&t, b); mp_clear (&t); return MP_OKAY; }
/* ** 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; PRArenaPool *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 * 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; }
/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + * k2 * P(x, y), where G is the generator (base point) of the group of * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. * Input and output values are assumed to be NOT field-encoded. Uses * algorithm 15 (simultaneous multiple point multiplication) from Brown, * Hankerson, Lopez, Menezes. Software Implementation of the NIST * Elliptic Curves over Prime Fields. */ mp_err ec_pts_mul_simul_w2(const mp_int *k1, const mp_int *k2, const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry, const ECGroup *group) { mp_err res = MP_OKAY; mp_int precomp[4][4][2]; const mp_int *a, *b; int i, j; int ai, bi, d; ARGCHK(group != NULL, MP_BADARG); ARGCHK(!((k1 == NULL) && ((k2 == NULL) || (px == NULL) || (py == NULL))), MP_BADARG); /* if some arguments are not defined used ECPoint_mul */ if (k1 == NULL) { return ECPoint_mul(group, k2, px, py, rx, ry); } else if ((k2 == NULL) || (px == NULL) || (py == NULL)) { return ECPoint_mul(group, k1, NULL, NULL, rx, ry); } /* initialize precomputation table */ for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { MP_DIGITS(&precomp[i][j][0]) = 0; MP_DIGITS(&precomp[i][j][1]) = 0; } } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { MP_CHECKOK( mp_init_size(&precomp[i][j][0], ECL_MAX_FIELD_SIZE_DIGITS, FLAG(k1)) ); MP_CHECKOK( mp_init_size(&precomp[i][j][1], ECL_MAX_FIELD_SIZE_DIGITS, FLAG(k1)) ); } } /* fill precomputation table */ /* assign {k1, k2} = {a, b} such that len(a) >= len(b) */ if (mpl_significant_bits(k1) < mpl_significant_bits(k2)) { a = k2; b = k1; if (group->meth->field_enc) { MP_CHECKOK(group->meth-> field_enc(px, &precomp[1][0][0], group->meth)); MP_CHECKOK(group->meth-> field_enc(py, &precomp[1][0][1], group->meth)); } else { MP_CHECKOK(mp_copy(px, &precomp[1][0][0])); MP_CHECKOK(mp_copy(py, &precomp[1][0][1])); } MP_CHECKOK(mp_copy(&group->genx, &precomp[0][1][0])); MP_CHECKOK(mp_copy(&group->geny, &precomp[0][1][1])); } else { a = k1; b = k2; MP_CHECKOK(mp_copy(&group->genx, &precomp[1][0][0])); MP_CHECKOK(mp_copy(&group->geny, &precomp[1][0][1])); if (group->meth->field_enc) { MP_CHECKOK(group->meth-> field_enc(px, &precomp[0][1][0], group->meth)); MP_CHECKOK(group->meth-> field_enc(py, &precomp[0][1][1], group->meth)); } else { MP_CHECKOK(mp_copy(px, &precomp[0][1][0])); MP_CHECKOK(mp_copy(py, &precomp[0][1][1])); } } /* precompute [*][0][*] */ mp_zero(&precomp[0][0][0]); mp_zero(&precomp[0][0][1]); MP_CHECKOK(group-> point_dbl(&precomp[1][0][0], &precomp[1][0][1], &precomp[2][0][0], &precomp[2][0][1], group)); MP_CHECKOK(group-> point_add(&precomp[1][0][0], &precomp[1][0][1], &precomp[2][0][0], &precomp[2][0][1], &precomp[3][0][0], &precomp[3][0][1], group)); /* precompute [*][1][*] */ for (i = 1; i < 4; i++) { MP_CHECKOK(group-> point_add(&precomp[0][1][0], &precomp[0][1][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][1][0], &precomp[i][1][1], group)); } /* precompute [*][2][*] */ MP_CHECKOK(group-> point_dbl(&precomp[0][1][0], &precomp[0][1][1], &precomp[0][2][0], &precomp[0][2][1], group)); for (i = 1; i < 4; i++) { MP_CHECKOK(group-> point_add(&precomp[0][2][0], &precomp[0][2][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][2][0], &precomp[i][2][1], group)); } /* precompute [*][3][*] */ MP_CHECKOK(group-> point_add(&precomp[0][1][0], &precomp[0][1][1], &precomp[0][2][0], &precomp[0][2][1], &precomp[0][3][0], &precomp[0][3][1], group)); for (i = 1; i < 4; i++) { MP_CHECKOK(group-> point_add(&precomp[0][3][0], &precomp[0][3][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][3][0], &precomp[i][3][1], group)); } d = (mpl_significant_bits(a) + 1) / 2; /* R = inf */ mp_zero(rx); mp_zero(ry); for (i = d - 1; i >= 0; i--) { ai = MP_GET_BIT(a, 2 * i + 1); ai <<= 1; ai |= MP_GET_BIT(a, 2 * i); bi = MP_GET_BIT(b, 2 * i + 1); bi <<= 1; bi |= MP_GET_BIT(b, 2 * i); /* R = 2^2 * R */ MP_CHECKOK(group->point_dbl(rx, ry, rx, ry, group)); MP_CHECKOK(group->point_dbl(rx, ry, rx, ry, group)); /* R = R + (ai * A + bi * B) */ MP_CHECKOK(group-> point_add(rx, ry, &precomp[ai][bi][0], &precomp[ai][bi][1], rx, ry, group)); } if (group->meth->field_dec) { MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); } CLEANUP: for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { mp_clear(&precomp[i][j][0]); mp_clear(&precomp[i][j][1]); } } return res; }
/* ** Performs an ECDH key derivation by computing the scalar point ** multiplication of privateValue and publicValue (with or without the ** cofactor) and returns the x-coordinate of the resulting elliptic ** curve point in derived secret. If successful, derivedSecret->data ** is set to the address of the newly allocated buffer containing the ** derived secret, and derivedSecret->len is the size of the secret ** produced. It is the caller's responsibility to free the allocated ** buffer containing the derived secret. */ SECStatus ECDH_Derive(SECItem *publicValue, ECParams *ecParams, SECItem *privateValue, PRBool withCofactor, SECItem *derivedSecret) { SECStatus rv = SECFailure; #ifdef NSS_ENABLE_ECC unsigned int len = 0; SECItem pointQ = {siBuffer, NULL, 0}; mp_int k; /* to hold the private value */ mp_int cofactor; mp_err err = MP_OKAY; #if EC_DEBUG int i; #endif if (!publicValue || !ecParams || !privateValue || !derivedSecret) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } MP_DIGITS(&k) = 0; memset(derivedSecret, 0, sizeof *derivedSecret); len = (ecParams->fieldID.size + 7) >> 3; pointQ.len = 2*len + 1; if ((pointQ.data = PORT_Alloc(2*len + 1)) == NULL) goto cleanup; CHECK_MPI_OK( mp_init(&k) ); CHECK_MPI_OK( mp_read_unsigned_octets(&k, privateValue->data, (mp_size) privateValue->len) ); if (withCofactor && (ecParams->cofactor != 1)) { /* multiply k with the cofactor */ MP_DIGITS(&cofactor) = 0; CHECK_MPI_OK( mp_init(&cofactor) ); mp_set(&cofactor, ecParams->cofactor); CHECK_MPI_OK( mp_mul(&k, &cofactor, &k) ); } /* Multiply our private key and peer's public point */ if (ec_points_mul(ecParams, NULL, &k, publicValue, &pointQ) != SECSuccess) goto cleanup; if (ec_point_at_infinity(&pointQ)) { PORT_SetError(SEC_ERROR_BAD_KEY); /* XXX better error code? */ goto cleanup; } /* Allocate memory for the derived secret and copy * the x co-ordinate of pointQ into it. */ SECITEM_AllocItem(NULL, derivedSecret, len); memcpy(derivedSecret->data, pointQ.data + 1, len); rv = SECSuccess; #if EC_DEBUG printf("derived_secret:\n"); for (i = 0; i < derivedSecret->len; i++) printf("%02x:", derivedSecret->data[i]); printf("\n"); #endif cleanup: mp_clear(&k); if (err) { MP_TO_SEC_ERROR(err); } if (pointQ.data) { PORT_ZFree(pointQ.data, 2*len + 1); } #else PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); #endif /* NSS_ENABLE_ECC */ return rv; }