static int compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
	{
	BN_CTX *ctx=NULL;
	BN_MONT_CTX *mont=NULL;
	BIGNUM *tmp;
	int ret= -1;
        int check_result;

	if (BN_num_bits(dh->p) > OPENSSL_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 (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_EXP_CONSTTIME);
			}
		if (!mont)
			goto err;
		}

        if (!DH_check_pub_key(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);
	}