int DH_compute_key(unsigned char *shared_key, const BIGNUM *peer_pub_key, DH *dh) { int codes; /** * Checks that the pubkey passed in is valid using * DH_check_pubkey(). */ if (!DH_check_pubkey(dh, peer_pub_key, &codes) || codes != 0) return -1; return dh->meth->compute_key(shared_key, peer_pub_key, dh); }
static int ltm_dh_generate_key(DH *dh) { mp_int pub, priv_key, g, p; int have_private_key = (dh->priv_key != NULL); int codes, times = 0; int res; if (dh->p == NULL || dh->g == NULL) return 0; while (times++ < DH_NUM_TRIES) { if (!have_private_key) { size_t bits = BN_num_bits(dh->p); if (dh->priv_key) BN_free(dh->priv_key); dh->priv_key = BN_new(); if (dh->priv_key == NULL) return 0; if (!BN_rand(dh->priv_key, bits - 1, 0, 0)) { BN_clear_free(dh->priv_key); dh->priv_key = NULL; return 0; } } if (dh->pub_key) BN_free(dh->pub_key); mp_init_multi(&pub, &priv_key, &g, &p, NULL); BN2mpz(&priv_key, dh->priv_key); BN2mpz(&g, dh->g); BN2mpz(&p, dh->p); res = mp_exptmod(&g, &priv_key, &p, &pub); mp_clear_multi(&priv_key, &g, &p, NULL); if (res != 0) continue; dh->pub_key = mpz2BN(&pub); mp_clear(&pub); if (dh->pub_key == NULL) return 0; if (DH_check_pubkey(dh, dh->pub_key, &codes) && codes == 0) break; if (have_private_key) return 0; } if (times >= DH_NUM_TRIES) { if (!have_private_key && dh->priv_key) { BN_free(dh->priv_key); dh->priv_key = NULL; } if (dh->pub_key) { BN_free(dh->pub_key); dh->pub_key = NULL; } return 0; } return 1; }
static int eay_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) { BN_CTX *ctx = NULL; #if 0 BN_MONT_CTX *mont = NULL; #endif BIGNUM *tmp; int ret = -1; int check_result; if (BN_num_bits(dh->p) > DH_MAX_MODULUS_BITS) { /* DHerr(DH_F_COMPUTE_KEY,DH_R_MODULUS_TOO_LARGE); */ goto err; } ctx = BN_CTX_new(); if (ctx == NULL) { goto err; } BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (dh->priv_key == NULL) { /* DHerr(DH_F_COMPUTE_KEY,DH_R_NO_PRIVATE_VALUE); */ goto err; } #if 0 if (dh->flags & DH_FLAG_CACHE_MONT_P) { mont = BN_MONT_CTX_set_locked(&dh->method_mont_p, CRYPTO_LOCK_DH, dh->p, ctx); if ((dh->flags & DH_FLAG_NO_EXP_CONSTTIME) == 0) { /* XXX */ BN_set_flags(dh->priv_key, BN_FLG_CONSTTIME); } if (!mont) { goto err; } } #endif if (!DH_check_pubkey(dh, pub_key, &check_result) || check_result) { /* DHerr(DH_F_COMPUTE_KEY,DH_R_INVALID_PUBKEY); */ goto err; } if (!dh->meth->bn_mod_exp(dh, tmp, pub_key, dh->priv_key, dh->p, ctx /*, mont */)) { /* DHerr(DH_F_COMPUTE_KEY,ERR_R_BN_LIB); */ goto err; } ret = BN_bn2bin(tmp, key); err: if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return (ret); }