Example #1
0
		bool GenerateRSAKeyPair(int numBits, std::string& privKey, std::string& pubKey)
		{
			// TODO: add some error checking
			RSA* rsa = RSA_new();
			BIGNUM* bn = BN_new();
			BN_GENCB cb;
			BIO* bio_err = NULL;
			BN_GENCB_set(&cb, genrsa_cb, bio_err);
			BN_set_word(bn, RSA_F4);
			RSA_generate_key_ex(rsa, numBits, bn, &cb);

			BIO* privKeyBuff = BIO_new(BIO_s_mem());
			BIO* pubKeyBuff = BIO_new(BIO_s_mem());
			PEM_write_bio_RSAPrivateKey(privKeyBuff, rsa, 0, 0, 0, 0, 0);
			PEM_write_bio_RSA_PUBKEY(pubKeyBuff, rsa); // RSA_PUBKEY includes some data that RSAPublicKey doesn't have

			char* privKeyData;
			char* pubKeyData;
			auto privKeySize = BIO_get_mem_data(privKeyBuff, &privKeyData);
			auto pubKeySize = BIO_get_mem_data(pubKeyBuff, &pubKeyData);

			privKey = std::string(privKeyData, privKeySize);
			pubKey = std::string(pubKeyData, pubKeySize);
			
			BIO_free_all(privKeyBuff);
			BIO_free_all(pubKeyBuff);
			BN_free(bn);
			RSA_free(rsa);
			return true;
		}
Example #2
0
static isc_result_t
openssldsa_generate(dst_key_t *key, int unused, void (*callback)(int)) {
	DSA *dsa;
	unsigned char rand_array[ISC_SHA1_DIGESTLENGTH];
	isc_result_t result;
#if OPENSSL_VERSION_NUMBER > 0x00908000L
	BN_GENCB cb;
	union {
		void *dptr;
		void (*fptr)(int);
	} u;

#else

	UNUSED(callback);
#endif
	UNUSED(unused);

	result = dst__entropy_getdata(rand_array, sizeof(rand_array),
				      ISC_FALSE);
	if (result != ISC_R_SUCCESS)
		return (result);

#if OPENSSL_VERSION_NUMBER > 0x00908000L
	dsa = DSA_new();
	if (dsa == NULL)
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));

	if (callback == NULL) {
		BN_GENCB_set_old(&cb, NULL, NULL);
	} else {
		u.fptr = callback;
		BN_GENCB_set(&cb, &progress_cb, u.dptr);
	}

	if (!DSA_generate_parameters_ex(dsa, key->key_size, rand_array,
					ISC_SHA1_DIGESTLENGTH,  NULL, NULL,
					&cb))
	{
		DSA_free(dsa);
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
	}
#else
	dsa = DSA_generate_parameters(key->key_size, rand_array,
				      ISC_SHA1_DIGESTLENGTH, NULL, NULL,
				      NULL, NULL);
	if (dsa == NULL)
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
#endif

	if (DSA_generate_key(dsa) == 0) {
		DSA_free(dsa);
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
	}
	dsa->flags &= ~DSA_FLAG_CACHE_MONT_P;

	key->keydata.dsa = dsa;

	return (ISC_R_SUCCESS);
}
Example #3
0
File: rsa.c Project: KennethL/otp
static ERL_NIF_TERM rsa_generate_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{/* (ModulusSize, PublicExponent) */
    int modulus_bits;
    BIGNUM *pub_exp, *three;
    RSA *rsa;
    int success;
    ERL_NIF_TERM result;
    BN_GENCB *intr_cb;
#ifndef HAVE_OPAQUE_BN_GENCB
    BN_GENCB intr_cb_buf;
#endif

    if (!enif_get_int(env, argv[0], &modulus_bits) || modulus_bits < 256) {
	return enif_make_badarg(env);
    }

    if (!get_bn_from_bin(env, argv[1], &pub_exp)) {
	return enif_make_badarg(env);
    }

    /* Make sure the public exponent is large enough (at least 3).
     * Without this, RSA_generate_key_ex() can run forever. */
    three = BN_new();
    BN_set_word(three, 3);
    success = BN_cmp(pub_exp, three);
    BN_free(three);
    if (success < 0) {
	BN_free(pub_exp);
	return enif_make_badarg(env);
    }

    /* For large keys, prime generation can take many seconds. Set up
     * the callback which we use to test whether the process has been
     * interrupted. */
#ifdef HAVE_OPAQUE_BN_GENCB
    intr_cb = BN_GENCB_new();
#else
    intr_cb = &intr_cb_buf;
#endif
    BN_GENCB_set(intr_cb, check_erlang_interrupt, env);

    rsa = RSA_new();
    success = RSA_generate_key_ex(rsa, modulus_bits, pub_exp, intr_cb);
    BN_free(pub_exp);

#ifdef HAVE_OPAQUE_BN_GENCB
    BN_GENCB_free(intr_cb);
#endif

    if (!success) {
        RSA_free(rsa);
	return atom_error;
    }

    result = put_rsa_private_key(env, rsa);
    RSA_free(rsa);

    return result;
}
Example #4
0
int genrsa_main(int argc, char **argv)
{
    BN_GENCB *cb = BN_GENCB_new();
    PW_CB_DATA cb_data;
    ENGINE *eng = NULL;
    BIGNUM *bn = BN_new();
    BIO *out = NULL;
    BIGNUM *e;
    RSA *rsa = NULL;
    const EVP_CIPHER *enc = NULL;
    int ret = 1, num = DEFBITS, private = 0;
    unsigned long f4 = RSA_F4;
    char *outfile = NULL, *passoutarg = NULL, *passout = NULL;
    char *inrand = NULL, *prog, *hexe, *dece;
    OPTION_CHOICE o;

    if (bn == NULL || cb == NULL)
        goto end;

    BN_GENCB_set(cb, genrsa_cb, bio_err);

    prog = opt_init(argc, argv, genrsa_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            ret = 0;
            opt_help(genrsa_options);
            goto end;
        case OPT_3:
            f4 = 3;
            break;
        case OPT_F4:
            f4 = RSA_F4;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENGINE:
            eng = setup_engine(opt_arg(), 0);
            break;
        case OPT_RAND:
            inrand = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &enc))
                goto end;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();
    private = 1;
Example #5
0
/*
 * Generate and store a private key on the token
 * FIXME: We should check first whether the token supports
 * on-board key generation, and if it does, use its own algorithm
 */
int pkcs11_generate_key(PKCS11_TOKEN *token, int algorithm, unsigned int bits,
		char *label, unsigned char* id, size_t id_len)
{
	PKCS11_KEY *key_obj;
	EVP_PKEY *pk;
	RSA *rsa;
	BIO *err;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
	BIGNUM *exp = NULL;
	BN_GENCB *gencb = NULL;
#endif
	int rc;

	if (algorithm != EVP_PKEY_RSA) {
		PKCS11err(PKCS11_F_PKCS11_GENERATE_KEY, PKCS11_NOT_SUPPORTED);
		return -1;
	}

	err = BIO_new_fp(stderr, BIO_NOCLOSE);

#if OPENSSL_VERSION_NUMBER >= 0x10100000L
	exp = BN_new();
	rsa = RSA_new();
	gencb = BN_GENCB_new();
	if (gencb)
	    BN_GENCB_set(gencb, NULL, err);

	if ( rsa == NULL  || exp == NULL || gencb == NULL
	    || !BN_set_word(exp, RSA_F4) || !RSA_generate_key_ex(rsa, bits, exp, gencb)) {
		RSA_free(rsa);
	}
	BN_GENCB_free(gencb);
	BN_free(exp);

#else
	rsa = RSA_generate_key(bits, RSA_F4, NULL, err);
#endif
	BIO_free(err);
	if (rsa == NULL) {
		PKCS11err(PKCS11_F_PKCS11_GENERATE_KEY, PKCS11_KEYGEN_FAILED);
		return -1;
	}

	pk = EVP_PKEY_new();
	EVP_PKEY_assign_RSA(pk, rsa);
	rc = pkcs11_store_key(token, pk, CKO_PRIVATE_KEY,
		label, id, id_len, &key_obj);

	if (rc == 0) {
		PKCS11_KEY_private *kpriv;

		kpriv = PRIVKEY(key_obj);
		rc = pkcs11_store_key(token, pk, CKO_PUBLIC_KEY,
			label, kpriv->id, kpriv->id_len, NULL);
	}
	EVP_PKEY_free(pk);
	return rc;
}
Example #6
0
int
isns_dsa_init_params(const char *filename)
{
	FILE	*fp;
	DSA	*dsa;
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
	BN_GENCB	*cb;
#endif
	const int dsa_key_bits = 1024;

	if (access(filename, R_OK) == 0)
		return 1;

	isns_mkdir_recursive(isns_dirname(filename));
	if (!(fp = fopen(filename, "w"))) {
		isns_error("Unable to open %s: %m\n", filename);
		return 0;
	}

	isns_notice("Generating DSA parameters; this may take a while\n");
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
	cb = BN_GENCB_new();
	BN_GENCB_set(cb, (int (*)(int, int, BN_GENCB *)) isns_dsa_param_gen_callback, NULL);
	dsa = DSA_new();
	if (!DSA_generate_parameters_ex(dsa, dsa_key_bits, NULL, 0, NULL, NULL, cb)) {
		DSA_free(dsa);
		dsa = NULL;
	}
	BN_GENCB_free(cb);
#else
	dsa = DSA_generate_parameters(dsa_key_bits, NULL, 0,
			NULL, NULL, isns_dsa_param_gen_callback, NULL);
#endif
	write(1, "\n", 1);

	if (dsa == NULL) {
		isns_dsasig_report_errors("Error generating DSA parameters",
				isns_error);
		fclose(fp);
		return 0;
	}

	if (!PEM_write_DSAparams(fp, dsa)) {
		isns_dsasig_report_errors("Error writing DSA parameters",
				isns_error);
		DSA_free(dsa);
		fclose(fp);
		return 0;
	}
	DSA_free(dsa);
	fclose(fp);
	return 1;
}
Example #7
0
static int dsa_test(void)
{
    BN_GENCB *cb;
    DSA *dsa = NULL;
    int counter, ret = 0, i, j;
    unsigned char buf[256];
    unsigned long h;
    unsigned char sig[256];
    unsigned int siglen;
    const BIGNUM *p = NULL, *q = NULL, *g = NULL;

    if (!TEST_ptr(cb = BN_GENCB_new()))
        goto end;

    BN_GENCB_set(cb, dsa_cb, NULL);
    if (!TEST_ptr(dsa = DSA_new())
        || !TEST_true(DSA_generate_parameters_ex(dsa, 512, seed, 20,
                                                &counter, &h, cb)))
        goto end;

    if (!TEST_int_eq(counter, 105))
        goto end;
    if (!TEST_int_eq(h, 2))
        goto end;

    DSA_get0_pqg(dsa, &p, &q, &g);
    i = BN_bn2bin(q, buf);
    j = sizeof(out_q);
    if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_q, i))
        goto end;

    i = BN_bn2bin(p, buf);
    j = sizeof(out_p);
    if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_p, i))
        goto end;

    i = BN_bn2bin(g, buf);
    j = sizeof(out_g);
    if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_g, i))
        goto end;

    DSA_generate_key(dsa);
    DSA_sign(0, str1, 20, sig, &siglen, dsa);
    if (TEST_true(DSA_verify(0, str1, 20, sig, siglen, dsa)))
        ret = 1;

 end:
    DSA_free(dsa);
    BN_GENCB_free(cb);
    return ret;
}
Example #8
0
static DH *
dh_generate(int size, int gen)
{
    struct ossl_generate_cb_arg cb_arg = { 0 };
    struct dh_blocking_gen_arg gen_arg;
    DH *dh = DH_new();
    BN_GENCB *cb = BN_GENCB_new();

    if (!dh || !cb) {
	DH_free(dh);
	BN_GENCB_free(cb);
	return NULL;
    }

    if (rb_block_given_p())
	cb_arg.yield = 1;
    BN_GENCB_set(cb, ossl_generate_cb_2, &cb_arg);
    gen_arg.dh = dh;
    gen_arg.size = size;
    gen_arg.gen = gen;
    gen_arg.cb = cb;
    if (cb_arg.yield == 1) {
	/* we cannot release GVL when callback proc is supplied */
	dh_blocking_gen(&gen_arg);
    } else {
	/* there's a chance to unblock */
	rb_thread_call_without_gvl(dh_blocking_gen, &gen_arg, ossl_generate_cb_stop, &cb_arg);
    }

    BN_GENCB_free(cb);
    if (!gen_arg.result) {
	DH_free(dh);
	if (cb_arg.state) {
	    /* Clear OpenSSL error queue before re-raising. */
	    ossl_clear_error();
	    rb_jump_tag(cb_arg.state);
	}
	return NULL;
    }

    if (!DH_generate_key(dh)) {
        DH_free(dh);
        return NULL;
    }

    return dh;
}
Example #9
0
static DH *
dh_generate(int size, int gen)
{
#if defined(HAVE_DH_GENERATE_PARAMETERS_EX) && HAVE_BN_GENCB
    BN_GENCB cb;
    struct ossl_generate_cb_arg cb_arg;
    struct dh_blocking_gen_arg gen_arg;
    DH *dh = DH_new();

    if (!dh) return 0;

    memset(&cb_arg, 0, sizeof(struct ossl_generate_cb_arg));
    if (rb_block_given_p())
	cb_arg.yield = 1;
    BN_GENCB_set(&cb, ossl_generate_cb_2, &cb_arg);
    gen_arg.dh = dh;
    gen_arg.size = size;
    gen_arg.gen = gen;
    gen_arg.cb = &cb;
    if (cb_arg.yield == 1) {
	/* we cannot release GVL when callback proc is supplied */
	dh_blocking_gen(&gen_arg);
    } else {
	/* there's a chance to unblock */
	rb_thread_call_without_gvl(dh_blocking_gen, &gen_arg, ossl_generate_cb_stop, &cb_arg);
    }

    if (!gen_arg.result) {
	DH_free(dh);
	if (cb_arg.state) rb_jump_tag(cb_arg.state);
	return 0;
    }
#else
    DH *dh;

    dh = DH_generate_parameters(size, gen, rb_block_given_p() ? ossl_generate_cb : NULL, NULL);
    if (!dh) return 0;
#endif

    if (!DH_generate_key(dh)) {
        DH_free(dh);
        return 0;
    }

    return dh;
}
Example #10
0
int
dhparam_main(int argc, char **argv)
{
	BIO *in = NULL, *out = NULL;
	char *num_bits = NULL;
	DH *dh = NULL;
	int num = 0;
	int ret = 1;
	int i;

	memset(&dhparam_config, 0, sizeof(dhparam_config));

	dhparam_config.informat = FORMAT_PEM;
	dhparam_config.outformat = FORMAT_PEM;

	if (options_parse(argc, argv, dhparam_options, &num_bits, NULL) != 0) {
		dhparam_usage();
		return (1);
	}

	if (num_bits != NULL) {
		if(sscanf(num_bits, "%d", &num) == 0 || num <= 0) {
			BIO_printf(bio_err, "invalid number of bits: %s\n",
			    num_bits);
			return (1);
		}
	}

	if (dhparam_config.g && !num)
		num = DEFBITS;

	if (dhparam_config.dsaparam) {
		if (dhparam_config.g) {
			BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n");
			goto end;
		}
	} else {
		/* DH parameters */
		if (num && !dhparam_config.g)
			dhparam_config.g = 2;
	}

	if (num) {

		BN_GENCB cb;
		BN_GENCB_set(&cb, dh_cb, bio_err);
		if (dhparam_config.dsaparam) {
			DSA *dsa = DSA_new();

			BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num);
			if (!dsa || !DSA_generate_parameters_ex(dsa, num,
				NULL, 0, NULL, NULL, &cb)) {
				if (dsa)
					DSA_free(dsa);
				ERR_print_errors(bio_err);
				goto end;
			}
			dh = DSA_dup_DH(dsa);
			DSA_free(dsa);
			if (dh == NULL) {
				ERR_print_errors(bio_err);
				goto end;
			}
		} else {
			dh = DH_new();
			BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, dhparam_config.g);
			BIO_printf(bio_err, "This is going to take a long time\n");
			if (!dh || !DH_generate_parameters_ex(dh, num, dhparam_config.g, &cb)) {
				ERR_print_errors(bio_err);
				goto end;
			}
		}
	} else {

		in = BIO_new(BIO_s_file());
		if (in == NULL) {
			ERR_print_errors(bio_err);
			goto end;
		}
		if (dhparam_config.infile == NULL)
			BIO_set_fp(in, stdin, BIO_NOCLOSE);
		else {
			if (BIO_read_filename(in, dhparam_config.infile) <= 0) {
				perror(dhparam_config.infile);
				goto end;
			}
		}

		if (dhparam_config.informat != FORMAT_ASN1 &&
		    dhparam_config.informat != FORMAT_PEM) {
			BIO_printf(bio_err, "bad input format specified\n");
			goto end;
		}
		if (dhparam_config.dsaparam) {
			DSA *dsa;

			if (dhparam_config.informat == FORMAT_ASN1)
				dsa = d2i_DSAparams_bio(in, NULL);
			else	/* informat == FORMAT_PEM */
				dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

			if (dsa == NULL) {
				BIO_printf(bio_err, "unable to load DSA parameters\n");
				ERR_print_errors(bio_err);
				goto end;
			}
			dh = DSA_dup_DH(dsa);
			DSA_free(dsa);
			if (dh == NULL) {
				ERR_print_errors(bio_err);
				goto end;
			}
		} else
		{
			if (dhparam_config.informat == FORMAT_ASN1)
				dh = d2i_DHparams_bio(in, NULL);
			else	/* informat == FORMAT_PEM */
				dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

			if (dh == NULL) {
				BIO_printf(bio_err, "unable to load DH parameters\n");
				ERR_print_errors(bio_err);
				goto end;
			}
		}

		/* dh != NULL */
	}

	out = BIO_new(BIO_s_file());
	if (out == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (dhparam_config.outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, dhparam_config.outfile) <= 0) {
			perror(dhparam_config.outfile);
			goto end;
		}
	}


	if (dhparam_config.text) {
		DHparams_print(out, dh);
	}
	if (dhparam_config.check) {
		if (!DH_check(dh, &i)) {
			ERR_print_errors(bio_err);
			goto end;
		}
		if (i & DH_CHECK_P_NOT_PRIME)
			printf("p value is not prime\n");
		if (i & DH_CHECK_P_NOT_SAFE_PRIME)
			printf("p value is not a safe prime\n");
		if (i & DH_UNABLE_TO_CHECK_GENERATOR)
			printf("unable to check the generator value\n");
		if (i & DH_NOT_SUITABLE_GENERATOR)
			printf("the g value is not a generator\n");
		if (i == 0)
			printf("DH parameters appear to be ok.\n");
	}
	if (dhparam_config.C) {
		unsigned char *data;
		int len, l, bits;

		len = BN_num_bytes(dh->p);
		bits = BN_num_bits(dh->p);
		data = malloc(len);
		if (data == NULL) {
			perror("malloc");
			goto end;
		}
		printf("#ifndef HEADER_DH_H\n"
		    "#include <openssl/dh.h>\n"
		    "#endif\n");
		printf("DH *get_dh%d()\n\t{\n", bits);

		l = BN_bn2bin(dh->p, data);
		printf("\tstatic unsigned char dh%d_p[] = {", bits);
		for (i = 0; i < l; i++) {
			if ((i % 12) == 0)
				printf("\n\t\t");
			printf("0x%02X, ", data[i]);
		}
		printf("\n\t\t};\n");

		l = BN_bn2bin(dh->g, data);
		printf("\tstatic unsigned char dh%d_g[] = {", bits);
		for (i = 0; i < l; i++) {
			if ((i % 12) == 0)
				printf("\n\t\t");
			printf("0x%02X, ", data[i]);
		}
		printf("\n\t\t};\n");

		printf("\tDH *dh;\n\n");
		printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
		printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
		    bits, bits);
		printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
		    bits, bits);
		printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
		printf("\t\t{ DH_free(dh); return(NULL); }\n");
		if (dh->length)
			printf("\tdh->length = %ld;\n", dh->length);
		printf("\treturn(dh);\n\t}\n");
		free(data);
	}
	if (!dhparam_config.noout) {
		if (dhparam_config.outformat == FORMAT_ASN1)
			i = i2d_DHparams_bio(out, dh);
		else if (dhparam_config.outformat == FORMAT_PEM)
			i = PEM_write_bio_DHparams(out, dh);
		else {
			BIO_printf(bio_err, "bad output format specified for outfile\n");
			goto end;
		}
		if (!i) {
			BIO_printf(bio_err, "unable to write DH parameters\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	ret = 0;

end:
	BIO_free(in);
	if (out != NULL)
		BIO_free_all(out);
	if (dh != NULL)
		DH_free(dh);

	return (ret);
}
Example #11
0
void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx)
{
    BN_GENCB_set(cb, trans_cb, ctx);
}
Example #12
0
int MAIN(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    char *infile, *outfile, *prog;
    char *inrand = NULL;
    char *id = NULL;

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config(bio_err, NULL))
        goto end;

    outfile = NULL;

    prog = argv[0];
    argc--;
    argv++;
    while (argc >= 1) {
        if (strcmp(*argv, "-inform") == 0) {
            if (--argc < 1)
                goto bad;
            informat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-outform") == 0) {
            if (--argc < 1)
                goto bad;
            outformat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-in") == 0) {
            if (--argc < 1)
                goto bad;
            infile = *(++argv);
        } else if (strcmp(*argv, "-out") == 0) {
            if (--argc < 1)
                goto bad;
            outfile = *(++argv);
        }
        else if (strcmp(*argv, "-check") == 0)
            check = 1;
        else if (strcmp(*argv, "-text") == 0)
            text = 1;
        else if (strcmp(*argv, "-dsaparam") == 0)
            dsaparam = 1;
        else if (strcmp(*argv, "-C") == 0)
            C = 1;
        else if (strcmp(*argv, "-noout") == 0)
            noout = 1;
        else if (strcmp(*argv, "-2") == 0)
            g = 2;
        else if (strcmp(*argv, "-5") == 0)
            g = 5;
        else if (strcmp(*argv, "-rand") == 0) {
            if (--argc < 1)
                goto bad;
            inrand = *(++argv);
        } else if (((sscanf(*argv, "%d", &num) == 0) || (num <= 0)))
            goto bad;
        argv++;
        argc--;
    }

    if (badops) {
 bad:
        BIO_printf(bio_err, "%s [options] [numbits]\n", prog);
        BIO_printf(bio_err, "where options are\n");
        BIO_printf(bio_err, " -inform arg   input format - one of DER PEM\n");
        BIO_printf(bio_err,
                   " -outform arg  output format - one of DER PEM\n");
        BIO_printf(bio_err, " -in arg       input file\n");
        BIO_printf(bio_err, " -out arg      output file\n");
        BIO_printf(bio_err,
                   " -dsaparam     read or generate DSA parameters, convert to DH\n");
        BIO_printf(bio_err, " -check        check the DH parameters\n");
        BIO_printf(bio_err,
                   " -text         print a text form of the DH parameters\n");
        BIO_printf(bio_err, " -C            Output C code\n");
        BIO_printf(bio_err,
                   " -2            generate parameters using  2 as the generator value\n");
        BIO_printf(bio_err,
                   " -5            generate parameters using  5 as the generator value\n");
        BIO_printf(bio_err,
                   " numbits       number of bits in to generate (default 2048)\n");
        BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
                   LIST_SEPARATOR_CHAR);
        BIO_printf(bio_err,
                   "               - load the file (or the files in the directory) into\n");
        BIO_printf(bio_err, "               the random number generator\n");
        BIO_printf(bio_err, " -noout        no output\n");
        goto end;
    }

    ERR_load_crypto_strings();

    if (g && !num)
        num = DEFBITS;

    if (dsaparam) {
        if (g) {
            BIO_printf(bio_err,
                       "generator may not be chosen for DSA parameters\n");
            goto end;
        }
    } else
    {
        /* DH parameters */
        if (num && !g)
            g = 2;
    }

    if (num) {

        BN_GENCB cb;
        BN_GENCB_set(&cb, dh_cb, bio_err);
        if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) {
            BIO_printf(bio_err,
                       "warning, not much extra random data, consider using the -rand option\n");
        }
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (!dsa
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               &cb)) {
                if (dsa)
                    DSA_free(dsa);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (!dh || !DH_generate_parameters_ex(dh, num, g, &cb)) {
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        app_RAND_write_file(NULL, bio_err);
    } else {

        in = BIO_new(BIO_s_file());
        if (in == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (infile == NULL)
            BIO_set_fp(in, stdin, BIO_NOCLOSE);
        else {
            if (BIO_read_filename(in, infile) <= 0) {
                perror(infile);
                goto end;
            }
        }

        if (informat != FORMAT_ASN1 && informat != FORMAT_PEM) {
            BIO_printf(bio_err, "bad input format specified\n");
            goto end;
        }
# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1)
                dh = d2i_DHparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    out = BIO_new(BIO_s_file());
    if (out == NULL) {
        ERR_print_errors(bio_err);
        goto end;
    }
    if (outfile == NULL) {
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
    } else {
        if (BIO_write_filename(out, outfile) <= 0) {
            perror(outfile);
            goto end;
        }
    }

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (C) {
        unsigned char *data;
        int len, l, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = (unsigned char *)OPENSSL_malloc(len);
        if (data == NULL) {
            perror("OPENSSL_malloc");
            goto end;
        }
        printf("#ifndef HEADER_DH_H\n"
               "#include <openssl/dh.h>\n" "#endif\n");
        printf("DH *get_dh%d()\n\t{\n", bits);

        l = BN_bn2bin(dh->p, data);
        printf("\tstatic unsigned char dh%d_p[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t\t};\n");

        l = BN_bn2bin(dh->g, data);
        printf("\tstatic unsigned char dh%d_g[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t\t};\n");

        printf("\tDH *dh;\n\n");
        printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n");
        printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n",
               bits, bits);
        printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n",
               bits, bits);
        printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
        printf("\t\t{ DH_free(dh); return(NULL); }\n");
        if (dh->length)
            printf("\tdh->length = %ld;\n", dh->length);
        printf("\treturn(dh);\n\t}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        if (outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (outformat == FORMAT_PEM) {
            if (dh->q)
                i = PEM_write_bio_DHxparams(out, dh);
            else
                i = PEM_write_bio_DHparams(out, dh);
        } else {
            BIO_printf(bio_err, "bad output format specified for outfile\n");
            goto end;
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    if (in != NULL)
        BIO_free(in);
    if (out != NULL)
        BIO_free_all(out);
    if (dh != NULL)
        DH_free(dh);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Example #13
0
int main(int argc, char **argv)
{
    BN_GENCB *cb;
    DSA *dsa = NULL;
    int counter, ret = 0, i, j;
    unsigned char buf[256];
    unsigned long h;
    unsigned char sig[256];
    unsigned int siglen;
    BIGNUM *p = NULL, *q = NULL, *g = NULL;

    if (bio_err == NULL)
        bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    CRYPTO_set_mem_debug(1);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    RAND_seed(rnd_seed, sizeof rnd_seed);

    BIO_printf(bio_err, "test generation of DSA parameters\n");

    cb = BN_GENCB_new();
    if (!cb)
        goto end;

    BN_GENCB_set(cb, dsa_cb, bio_err);
    if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512,
                                                                   seed, 20,
                                                                   &counter,
                                                                   &h, cb))
        goto end;

    BIO_printf(bio_err, "seed\n");
    for (i = 0; i < 20; i += 4) {
        BIO_printf(bio_err, "%02X%02X%02X%02X ",
                   seed[i], seed[i + 1], seed[i + 2], seed[i + 3]);
    }
    BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h);

    DSA_print(bio_err, dsa, 0);
    if (counter != 105) {
        BIO_printf(bio_err, "counter should be 105\n");
        goto end;
    }
    if (h != 2) {
        BIO_printf(bio_err, "h should be 2\n");
        goto end;
    }

    DSA_get0_pqg(dsa, &p, &q, &g);
    i = BN_bn2bin(q, buf);
    j = sizeof(out_q);
    if ((i != j) || (memcmp(buf, out_q, i) != 0)) {
        BIO_printf(bio_err, "q value is wrong\n");
        goto end;
    }

    i = BN_bn2bin(p, buf);
    j = sizeof(out_p);
    if ((i != j) || (memcmp(buf, out_p, i) != 0)) {
        BIO_printf(bio_err, "p value is wrong\n");
        goto end;
    }

    i = BN_bn2bin(g, buf);
    j = sizeof(out_g);
    if ((i != j) || (memcmp(buf, out_g, i) != 0)) {
        BIO_printf(bio_err, "g value is wrong\n");
        goto end;
    }

    DSA_set_flags(dsa, DSA_FLAG_NO_EXP_CONSTTIME);
    DSA_generate_key(dsa);
    DSA_sign(0, str1, 20, sig, &siglen, dsa);
    if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
        ret = 1;

    DSA_clear_flags(dsa, DSA_FLAG_NO_EXP_CONSTTIME);
    DSA_generate_key(dsa);
    DSA_sign(0, str1, 20, sig, &siglen, dsa);
    if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
        ret = 1;

 end:
    if (!ret)
        ERR_print_errors(bio_err);
    DSA_free(dsa);
    BN_GENCB_free(cb);

#ifndef OPENSSL_NO_CRYPTO_MDEBUG
    if (CRYPTO_mem_leaks(bio_err) <= 0)
        ret = 0;
#endif
    BIO_free(bio_err);
    bio_err = NULL;
    EXIT(!ret);
}
Example #14
0
int
main(int argc, char **argv)
{
    ENGINE *engine = NULL;
    int i, j, idx = 0;
    RSA *rsa;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
	usage(1);

    if (help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= idx;
    argv += idx;

    OpenSSL_add_all_algorithms();
#ifdef OPENSSL
    ENGINE_load_openssl();
#endif
    ENGINE_load_builtin_engines();

    if (argc == 0) {
	engine = ENGINE_by_id("builtin");
    } else {
	engine = ENGINE_by_id(argv[0]);
	if (engine == NULL)
	    engine = ENGINE_by_dso(argv[0], id_flag);
    }
    if (engine == NULL)
	errx(1, "ENGINE_by_dso failed");

    if (ENGINE_get_RSA(engine) == NULL)
	return 77;

    printf("rsa %s\n", ENGINE_get_RSA(engine)->name);

    if (RAND_status() != 1)
	errx(77, "no functional random device, refusing to run tests");

    if (time_keygen) {
	struct timeval tv1, tv2;
	BIGNUM *e;

	rsa = RSA_new_method(engine);
	if (!key_blinding)
	    rsa->flags |= RSA_FLAG_NO_BLINDING;

	e = BN_new();
	BN_set_word(e, 0x10001);

	printf("running keygen with %d loops\n", loops);

	gettimeofday(&tv1, NULL);

	for (i = 0; i < loops; i++) {
	    rsa = RSA_new_method(engine);
	    if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1)
		errx(1, "RSA_generate_key_ex");
	    RSA_free(rsa);
	}

	gettimeofday(&tv2, NULL);
	timevalsub(&tv2, &tv1);

	printf("time %lu.%06lu\n",
	       (unsigned long)tv2.tv_sec,
	       (unsigned long)tv2.tv_usec);

	BN_free(e);
	ENGINE_finish(engine);

	return 0;
    }

    if (time_key) {
	const int size = 20;
	struct timeval tv1, tv2;
	unsigned char *p;

	if (strcmp(time_key, "generate") == 0) {
	    BIGNUM *e;

	    rsa = RSA_new_method(engine);
	    if (!key_blinding)
		rsa->flags |= RSA_FLAG_NO_BLINDING;

	    e = BN_new();
	    BN_set_word(e, 0x10001);

	    if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1)
		errx(1, "RSA_generate_key_ex");
	} else {
	    rsa = read_key(engine, time_key);
	}

	p = emalloc(loops * size);

	RAND_bytes(p, loops * size);

	gettimeofday(&tv1, NULL);
	for (i = 0; i < loops; i++)
	    check_rsa(p + (i * size), size, rsa, RSA_PKCS1_PADDING);
	gettimeofday(&tv2, NULL);

	timevalsub(&tv2, &tv1);

	printf("time %lu.%06lu\n",
	       (unsigned long)tv2.tv_sec,
	       (unsigned long)tv2.tv_usec);

	RSA_free(rsa);
	ENGINE_finish(engine);

	return 0;
    }

    if (rsa_key) {
	rsa = read_key(engine, rsa_key);

	/*
	 * Assuming that you use the RSA key in the distribution, this
	 * test will generate a signature have a starting zero and thus
	 * will generate a checksum that is 127 byte instead of the
	 * checksum that is 128 byte (like the key).
	 */
	{
	    const unsigned char sha1[20] = {
		0x6d, 0x33, 0xf9, 0x40, 0x75, 0x5b, 0x4e, 0xc5, 0x90, 0x35,
		0x48, 0xab, 0x75, 0x02, 0x09, 0x76, 0x9a, 0xb4, 0x7d, 0x6b
	    };
	
	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}
	
	for (i = 0; i < 128; i++) {
	    unsigned char sha1[20];
	
	    RAND_bytes(sha1, sizeof(sha1));
	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}
	for (i = 0; i < 128; i++) {
	    unsigned char des3[21];

	    RAND_bytes(des3, sizeof(des3));
	    check_rsa(des3, sizeof(des3), rsa, RSA_PKCS1_PADDING);
	}
	for (i = 0; i < 128; i++) {
	    unsigned char aes[32];

	    RAND_bytes(aes, sizeof(aes));
	    check_rsa(aes, sizeof(aes), rsa, RSA_PKCS1_PADDING);
	}

	RSA_free(rsa);
    }

    for (i = 0; i < loops; i++) {
	BN_GENCB cb;
	BIGNUM *e;
	unsigned int n;

	rsa = RSA_new_method(engine);
	if (!key_blinding)
	    rsa->flags |= RSA_FLAG_NO_BLINDING;

	e = BN_new();
	BN_set_word(e, 0x10001);
	
	BN_GENCB_set(&cb, cb_func, NULL);
	
	RAND_bytes(&n, sizeof(n));
	n &= 0x1ff;
	n += 1024;

	if (RSA_generate_key_ex(rsa, n, e, &cb) != 1)
	    errx(1, "RSA_generate_key_ex");

	BN_free(e);
	
	for (j = 0; j < 8; j++) {
	    unsigned char sha1[20];
	    RAND_bytes(sha1, sizeof(sha1));
	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}

	RSA_free(rsa);
    }

    ENGINE_finish(engine);

    return 0;
}
Example #15
0
int
genrsa_main(int argc, char **argv)
{
	BN_GENCB cb;
	int ret = 1;
	int i, num = DEFBITS;
	long l;
	const EVP_CIPHER *enc = NULL;
	unsigned long f4 = RSA_F4;
	char *outfile = NULL;
	char *passargout = NULL, *passout = NULL;
	BIO *out = NULL;
	BIGNUM *bn = BN_new();
	RSA *rsa = NULL;

	if (single_execution) {
		if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	if (!bn)
		goto err;

	BN_GENCB_set(&cb, genrsa_cb, bio_err);

	if ((out = BIO_new(BIO_s_file())) == NULL) {
		BIO_printf(bio_err, "unable to create BIO for output\n");
		goto err;
	}
	argv++;
	argc--;
	for (;;) {
		if (argc <= 0)
			break;
		if (strcmp(*argv, "-out") == 0) {
			if (--argc < 1)
				goto bad;
			outfile = *(++argv);
		} else if (strcmp(*argv, "-3") == 0)
			f4 = 3;
		else if (strcmp(*argv, "-F4") == 0 || strcmp(*argv, "-f4") == 0)
			f4 = RSA_F4;
#ifndef OPENSSL_NO_DES
		else if (strcmp(*argv, "-des") == 0)
			enc = EVP_des_cbc();
		else if (strcmp(*argv, "-des3") == 0)
			enc = EVP_des_ede3_cbc();
#endif
#ifndef OPENSSL_NO_IDEA
		else if (strcmp(*argv, "-idea") == 0)
			enc = EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (strcmp(*argv, "-aes128") == 0)
			enc = EVP_aes_128_cbc();
		else if (strcmp(*argv, "-aes192") == 0)
			enc = EVP_aes_192_cbc();
		else if (strcmp(*argv, "-aes256") == 0)
			enc = EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (strcmp(*argv, "-camellia128") == 0)
			enc = EVP_camellia_128_cbc();
		else if (strcmp(*argv, "-camellia192") == 0)
			enc = EVP_camellia_192_cbc();
		else if (strcmp(*argv, "-camellia256") == 0)
			enc = EVP_camellia_256_cbc();
#endif
		else if (strcmp(*argv, "-passout") == 0) {
			if (--argc < 1)
				goto bad;
			passargout = *(++argv);
		} else
			break;
		argv++;
		argc--;
	}
	if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) {
 bad:
		BIO_printf(bio_err, "usage: genrsa [args] [numbits]\n");
		BIO_printf(bio_err, " -des            encrypt the generated key with DES in cbc mode\n");
		BIO_printf(bio_err, " -des3           encrypt the generated key with DES in ede cbc mode (168 bit key)\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err, " -idea           encrypt the generated key with IDEA in cbc mode\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err, " -aes128, -aes192, -aes256\n");
		BIO_printf(bio_err, "                 encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err, "                 encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err, " -out file       output the key to 'file\n");
		BIO_printf(bio_err, " -passout arg    output file pass phrase source\n");
		BIO_printf(bio_err, " -f4             use F4 (0x10001) for the E value\n");
		BIO_printf(bio_err, " -3              use 3 for the E value\n");
		goto err;
	}

	if (!app_passwd(bio_err, NULL, passargout, NULL, &passout)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto err;
	}

	if (outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, outfile) <= 0) {
			perror(outfile);
			goto err;
		}
	}

	BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus\n",
	    num);
	rsa = RSA_new();
	if (!rsa)
		goto err;

	if (!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb))
		goto err;

	/*
	 * We need to do the following for when the base number size is <
	 * long, esp windows 3.1 :-(.
	 */
	l = 0L;
	for (i = 0; i < rsa->e->top; i++) {
#ifndef _LP64
		l <<= BN_BITS4;
		l <<= BN_BITS4;
#endif
		l += rsa->e->d[i];
	}
	BIO_printf(bio_err, "e is %ld (0x%lX)\n", l, l);
	{
		PW_CB_DATA cb_data;
		cb_data.password = passout;
		cb_data.prompt_info = outfile;
		if (!PEM_write_bio_RSAPrivateKey(out, rsa, enc, NULL, 0,
			password_callback, &cb_data))
			goto err;
	}

	ret = 0;
 err:
	BN_free(bn);
	RSA_free(rsa);
	BIO_free_all(out);
	free(passout);

	if (ret != 0)
		ERR_print_errors(bio_err);

	return (ret);
}
Example #16
0
int dhparam_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    DH *dh = NULL;
    char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL;
#ifndef OPENSSL_NO_DSA
    int dsaparam = 0;
#endif
    int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, dhparam_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(dhparam_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        case OPT_CHECK:
            check = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_DSAPARAM:
#ifndef OPENSSL_NO_DSA
            dsaparam = 1;
#endif
            break;
        case OPT_C:
            C = 1;
            break;
        case OPT_2:
            g = 2;
            break;
        case OPT_5:
            g = 5;
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_RAND:
            inrand = opt_arg();
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (argv[0] && (!opt_int(argv[0], &num) || num <= 0))
        goto end;

    if (g && !num)
        num = DEFBITS;

# ifndef OPENSSL_NO_DSA
    if (dsaparam && g) {
        BIO_printf(bio_err,
                   "generator may not be chosen for DSA parameters\n");
        goto end;
    }
# endif
    /* DH parameters */
    if (num && !g)
        g = 2;

    if (num) {

        BN_GENCB *cb;
        cb = BN_GENCB_new();
        if (cb == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }

        BN_GENCB_set(cb, dh_cb, bio_err);
        if (!app_RAND_load_file(NULL, 1) && inrand == NULL) {
            BIO_printf(bio_err,
                       "warning, not much extra random data, consider using the -rand option\n");
        }
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (dsa == NULL
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               cb)) {
                DSA_free(dsa);
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (dh == NULL || !DH_generate_parameters_ex(dh, num, g, cb)) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        BN_GENCB_free(cb);
        app_RAND_write_file(NULL);
    } else {

        in = bio_open_default(infile, 'r', informat);
        if (in == NULL)
            goto end;

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1)
                dh = d2i_DHparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (C) {
        unsigned char *data;
        int len, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = app_malloc(len, "print a BN");
        BIO_printf(out, "#ifndef HEADER_DH_H\n"
                        "# include <openssl/dh.h>\n"
                        "#endif\n"
                        "\n");
        BIO_printf(out, "DH *get_dh%d()\n{\n", bits);
        print_bignum_var(out, dh->p, "dhp", bits, data);
        print_bignum_var(out, dh->g, "dhg", bits, data);
        BIO_printf(out, "    DH *dh = DN_new();\n"
                        "\n"
                        "    if (dh == NULL)\n"
                        "        return NULL;\n");
        BIO_printf(out, "    dh->p = BN_bin2bn(dhp_%d, sizeof (dhp_%d), NULL);\n",
               bits, bits);
        BIO_printf(out, "    dh->g = BN_bin2bn(dhg_%d, sizeof (dhg_%d), NULL);\n",
               bits, bits);
        BIO_printf(out, "    if (!dh->p || !dh->g) {\n"
                        "        DH_free(dh);\n"
                        "        return NULL;\n"
                        "    }\n");
        if (dh->length)
            BIO_printf(out,
                        "    dh->length = %ld;\n", dh->length);
        BIO_printf(out, "    return dh;\n}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        if (outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (dh->q)
            i = PEM_write_bio_DHxparams(out, dh);
        else
            i = PEM_write_bio_DHparams(out, dh);
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    BIO_free(in);
    BIO_free_all(out);
    DH_free(dh);
    return (ret);
}
Example #17
0
int
main(int argc, char **argv)
{
    ENGINE *engine = NULL;
    int i, j, idx = 0;
    RSA *rsa;

    setprogname(argv[0]);

    /*
    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
	usage(1);

    if (help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }
    */

    while(1) {
	    int c = getopt_long(argc, argv, "hq", args, &idx);

	    if (c == -1)
		    break;

	    switch (c) {
	    case 'q':
		    verbose = 0;
		    break;
	    case 'h':
		    usage(0);
		    break;
	    case '?':
	    default:
		    usage(-1);
		    break;
	    }
    }

    /*
    argc -= idx;
    argv += idx;
    */

    if (verbose) printf("[TEST] RSA\n");

    /* OpenSSL_add_all_algorithms(); */
#ifdef OPENSSL
    ENGINE_load_openssl();
#endif
    ENGINE_load_builtin_engines();

    /*
    if (argc == 0) {
	engine = ENGINE_by_id("builtin");
    } else {
	engine = ENGINE_by_id(argv[0]);
	if (engine == NULL)
	    engine = ENGINE_by_dso(argv[0], id_flag);
    }
    if (engine == NULL) {
	fprintf(stderr, "ENGINE_by_dso failed"\n);
	return 76;
    }

    if (ENGINE_get_RSA(engine) == NULL)
	return 77;

    printf("rsa %s\n", ENGINE_get_RSA(engine)->name);
    */

    if (time_keygen) {
	struct timeval tv1, tv2;
	BIGNUM *e;

	rsa = RSA_new_method(engine);
	if (!key_blinding)
	    rsa->flags |= RSA_FLAG_NO_BLINDING;

	e = BN_new();
	BN_set_word(e, 0x10001);

	printf("running keygen with %d loops\n", loops);

	gettimeofday(&tv1, NULL);

	for (i = 0; i < loops; i++) {
	    rsa = RSA_new_method(engine);
	    if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1) {
		RSA_free(rsa);
		fprintf(stderr, "RSA_generate_key_ex");
		fail++;
		return 1;
	    }
	    RSA_free(rsa);
	}

	gettimeofday(&tv2, NULL);
	timevalsub(&tv2, &tv1);

	printf("time %lu.%06lu\n",
	       (unsigned long)tv2.tv_sec,
	       (unsigned long)tv2.tv_usec);

	BN_free(e);
	/*
	ENGINE_finish(engine);
	*/

	return 0;
    }

/*
    if (time_key) {
	const int size = 20;
	struct timeval tv1, tv2;
	unsigned char *p;

	if (strcmp(time_key, "generate") == 0) {
	    BIGNUM *e;

	    rsa = RSA_new_method(engine);
	    if (!key_blinding)
		rsa->flags |= RSA_FLAG_NO_BLINDING;

	    e = BN_new();
	    BN_set_word(e, 0x10001);

	    if (RSA_generate_key_ex(rsa, 1024, e, NULL) != 1) {
		fprintf(stderr, "RSA_generate_key_ex");
		fail++;
		return (1);
	    }
	} else {
	    rsa = read_key(engine, time_key);
	}

	p = emalloc(loops * size);

	CCRandomCopyBytes(kCCRandomDefault, p, loops * size);

	gettimeofday(&tv1, NULL);
	for (i = 0; i < loops; i++)
	    check_rsa(p + (i * size), size, rsa, RSA_PKCS1_PADDING);
	gettimeofday(&tv2, NULL);

	timevalsub(&tv2, &tv1);

	printf("time %lu.%06lu\n",
	       (unsigned long)tv2.tv_sec,
	       (unsigned long)tv2.tv_usec);

	RSA_free(rsa);
	ENGINE_finish(engine);

	return 0;
    }
*/

    if (rsa_key) {
	rsa = read_key(engine, rsa_key);

	/*
	 * Assuming that you use the RSA key in the distribution, this
	 * test will generate a signature have a starting zero and thus
	 * will generate a checksum that is 127 byte instead of the
	 * checksum that is 128 byte (like the key).
	 */
	{
	    const unsigned char sha1[20] = {
		0x6d, 0x33, 0xf9, 0x40, 0x75, 0x5b, 0x4e, 0xc5, 0x90, 0x35,
		0x48, 0xab, 0x75, 0x02, 0x09, 0x76, 0x9a, 0xb4, 0x7d, 0x6b
	    };

	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}

	for (i = 0; i < 128; i++) {
	    unsigned char sha1[20];
	
	    CCRandomCopyBytes(kCCRandomDefault, sha1, sizeof(sha1));
	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}
	for (i = 0; i < 128; i++) {
	    unsigned char des3[21];

	    CCRandomCopyBytes(kCCRandomDefault, des3, sizeof(des3));
	    check_rsa(des3, sizeof(des3), rsa, RSA_PKCS1_PADDING);
	}
	for (i = 0; i < 128; i++) {
	    unsigned char aes[32];

	    CCRandomCopyBytes(kCCRandomDefault, aes, sizeof(aes));
	    check_rsa(aes, sizeof(aes), rsa, RSA_PKCS1_PADDING);
	}

	RSA_free(rsa);
    }

    if (verbose) {
	    printf("[BEGIN] RSA loops\n");
	    printf("Running %d loops\n", loops);
    }
    total++;
    for (i = 0; i < loops; i++) {
	BN_GENCB cb;
	BIGNUM *e;
	unsigned int n;

	rsa = RSA_new_method(engine);
	if (!key_blinding)
	    rsa->flags |= RSA_FLAG_NO_BLINDING;

	e = BN_new();
	BN_set_word(e, 0x10001);

	BN_GENCB_set(&cb, cb_func, NULL);
	
	CCRandomCopyBytes(kCCRandomDefault, &n, sizeof(n));
	n &= 0x1ff;
	n += 1024;

	if (RSA_generate_key_ex(rsa, n, e, &cb) != 1) {
	    fprintf(stderr, "RSA_generate_key_ex");
	    fail++;
	    return 1;
	}

	BN_free(e);

	for (j = 0; j < 8; j++) {
	    unsigned char sha1[20];
	    CCRandomCopyBytes(kCCRandomDefault, sha1, sizeof(sha1));
	    check_rsa(sha1, sizeof(sha1), rsa, RSA_PKCS1_PADDING);
	}

	RSA_free(rsa);
    }

    if (verbose) printf("[PASS] RSA loops\n");
    pass++;


    if (verbose) {
	    printf("[SUMMARY]\n");
	    printf("total: %d\n", total);
	    printf("passed: %d\n", pass);
	    printf("failed: %d\n", fail);
    }

    /* ENGINE_finish(engine); */

    return (fail);
}
Example #18
0
void Server::initializeCert() {
	QByteArray crt, key, pass, dhparams;

	crt = getConf("certificate", QString()).toByteArray();
	key = getConf("key", QString()).toByteArray();
	pass = getConf("passphrase", QByteArray()).toByteArray();
	dhparams = getConf("sslDHParams", Meta::mp.qbaDHParams).toByteArray();

	QList<QSslCertificate> ql;

	if (! key.isEmpty()) {
		qskKey = QSslKey(key, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass);
		if (qskKey.isNull())
			qskKey = QSslKey(key, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass);
	}
	if (qskKey.isNull() && ! crt.isEmpty()) {
		qskKey = QSslKey(crt, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass);
		if (qskKey.isNull())
			qskKey = QSslKey(crt, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass);
	}
	if (! qskKey.isNull()) {
		ql << QSslCertificate::fromData(crt);
		ql << QSslCertificate::fromData(key);
		for (int i=0;i<ql.size();++i) {
			const QSslCertificate &c = ql.at(i);
			if (isKeyForCert(qskKey, c)) {
				qscCert = c;
				ql.removeAt(i);
			}
		}
		qlCA = ql;
	}

#if defined(USE_QSSLDIFFIEHELLMANPARAMETERS)
	if (! dhparams.isEmpty()) {
		QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters(dhparams);
		if (qdhp.isValid()) {
			qsdhpDHParams = qdhp;
		} else {
			log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1").arg(qdhp.errorString()));
		}
	}
#else
	if (! dhparams.isEmpty()) {
		log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does not support Diffie-Hellman parameters.");
	}
#endif

	QString issuer;
#if QT_VERSION >= 0x050000
	QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName);
	if (! issuerNames.isEmpty()) {
		issuer = issuerNames.first();
	}
#else
	issuer = qscCert.issuerInfo(QSslCertificate::CommonName);
#endif

	if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) {
		log("Old autogenerated certificate is unusable for registration, invalidating it");
		qscCert = QSslCertificate();
		qskKey = QSslKey();
	}

	if (!qscCert.isNull() && issuer == QString::fromUtf8("Murmur Autogenerated Certificate v2") && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) {
		qscCert = Meta::mp.qscCert;
		qskKey = Meta::mp.qskKey;
	}

	if (qscCert.isNull() || qskKey.isNull()) {
		if (! key.isEmpty() || ! crt.isEmpty()) {
			log("Certificate specified, but failed to load.");
		}
		qskKey = Meta::mp.qskKey;
		qscCert = Meta::mp.qscCert;
		if (qscCert.isNull() || qskKey.isNull()) {
			log("Generating new server certificate.");

			CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

			X509 *x509 = X509_new();
			EVP_PKEY *pkey = EVP_PKEY_new();
			RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL);
			EVP_PKEY_assign_RSA(pkey, rsa);

			X509_set_version(x509, 2);
			ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
			X509_gmtime_adj(X509_get_notBefore(x509),0);
			X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20);
			X509_set_pubkey(x509, pkey);

			X509_NAME *name=X509_get_subject_name(x509);

			X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(const_cast<char *>("Murmur Autogenerated Certificate v2")), -1, -1, 0);
			X509_set_issuer_name(x509, name);
			add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE"));
			add_ext(x509, NID_ext_key_usage, SSL_STRING("serverAuth,clientAuth"));
			add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash"));
			add_ext(x509, NID_netscape_comment, SSL_STRING("Generated from murmur"));

			X509_sign(x509, pkey, EVP_sha1());

			crt.resize(i2d_X509(x509, NULL));
			unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data());
			i2d_X509(x509, &dptr);

			qscCert = QSslCertificate(crt, QSsl::Der);
			if (qscCert.isNull())
				log("Certificate generation failed");

			key.resize(i2d_PrivateKey(pkey, NULL));
			dptr=reinterpret_cast<unsigned char *>(key.data());
			i2d_PrivateKey(pkey, &dptr);

			qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der);
			if (qskKey.isNull())
				log("Key generation failed");

			setConf("certificate", qscCert.toPem());
			setConf("key", qskKey.toPem());
		}
	}

#if defined(USE_QSSLDIFFIEHELLMANPARAMETERS)
	if (qsdhpDHParams.isEmpty()) {
		log("Generating new server 2048-bit Diffie-Hellman parameters. This could take a while...");

		DH *dh = DH_new();
		if (dh == NULL) {
			qFatal("DH_new failed: unable to generate Diffie-Hellman parameters for virtual server");
		}

		// Generate DH params.
		// We register a status callback in order to update the UI
		// for Murmur on Windows. We don't show the actual status,
		// but we do it to keep Murmur on Windows responsive while
		// generating the parameters.
		BN_GENCB cb;
		memset(&cb, 0, sizeof(BN_GENCB));
		BN_GENCB_set(&cb, dh_progress, NULL);
		if (DH_generate_parameters_ex(dh, 2048, 2, &cb) == 0) {
			qFatal("DH_generate_parameters_ex failed: unable to generate Diffie-Hellman parameters for virtual server");
		}

		BIO *mem = BIO_new(BIO_s_mem());
		if (PEM_write_bio_DHparams(mem, dh) == 0) {
			qFatal("PEM_write_bio_DHparams failed: unable to write generated Diffie-Hellman parameters to memory");
		}

		char *pem = NULL;
		long len = BIO_get_mem_data(mem, &pem);
		if (len <= 0) {
			qFatal("BIO_get_mem_data returned an empty or invalid buffer");
		}

		QByteArray pemdh(pem, len);
		QSslDiffieHellmanParameters qdhp(pemdh);
		if (!qdhp.isValid()) {
			qFatal("QSslDiffieHellmanParameters: unable to import generated Diffie-HellmanParameters: %s", qdhp.errorString().toStdString().c_str());
		}

		qsdhpDHParams = qdhp;
		setConf("sslDHParams", pemdh);

		BIO_free(mem);
		DH_free(dh);
	}
#endif
}
Example #19
0
int dhparam_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    DH *dh = NULL;
    char *infile = NULL, *outfile = NULL, *prog;
    ENGINE *e = NULL;
#ifndef OPENSSL_NO_DSA
    int dsaparam = 0;
#endif
    int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, dhparam_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(dhparam_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_CHECK:
            check = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_DSAPARAM:
#ifndef OPENSSL_NO_DSA
            dsaparam = 1;
#endif
            break;
        case OPT_C:
            C = 1;
            break;
        case OPT_2:
            g = 2;
            break;
        case OPT_5:
            g = 5;
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_R_CASES:
            if (!opt_rand(o))
                goto end;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (argv[0] != NULL && (!opt_int(argv[0], &num) || num <= 0))
        goto end;

    if (g && !num)
        num = DEFBITS;

# ifndef OPENSSL_NO_DSA
    if (dsaparam && g) {
        BIO_printf(bio_err,
                   "generator may not be chosen for DSA parameters\n");
        goto end;
    }
# endif

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    /* DH parameters */
    if (num && !g)
        g = 2;

    if (num) {

        BN_GENCB *cb;
        cb = BN_GENCB_new();
        if (cb == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }

        BN_GENCB_set(cb, dh_cb, bio_err);

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (dsa == NULL
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               cb)) {
                DSA_free(dsa);
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (dh == NULL || !DH_generate_parameters_ex(dh, num, g, cb)) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        BN_GENCB_free(cb);
    } else {

        in = bio_open_default(infile, 'r', informat);
        if (in == NULL)
            goto end;

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1) {
                /*
                 * We have no PEM header to determine what type of DH params it
                 * is. We'll just try both.
                 */
                dh = d2i_DHparams_bio(in, NULL);
                /* BIO_reset() returns 0 for success for file BIOs only!!! */
                if (dh == NULL && BIO_reset(in) == 0)
                    dh = d2i_DHxparams_bio(in, NULL);
            } else {
                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
            }

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            BIO_printf(bio_err, "WARNING: p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            BIO_printf(bio_err, "WARNING: p value is not a safe prime\n");
        if (i & DH_CHECK_Q_NOT_PRIME)
            BIO_printf(bio_err, "WARNING: q value is not a prime\n");
        if (i & DH_CHECK_INVALID_Q_VALUE)
            BIO_printf(bio_err, "WARNING: q value is invalid\n");
        if (i & DH_CHECK_INVALID_J_VALUE)
            BIO_printf(bio_err, "WARNING: j value is invalid\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            BIO_printf(bio_err,
                       "WARNING: unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            BIO_printf(bio_err, "WARNING: the g value is not a generator\n");
        if (i == 0)
            BIO_printf(bio_err, "DH parameters appear to be ok.\n");
        if (num != 0 && i != 0) {
            /*
             * We have generated parameters but DH_check() indicates they are
             * invalid! This should never happen!
             */
            BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
            goto end;
        }
    }
    if (C) {
        unsigned char *data;
        int len, bits;
        const BIGNUM *pbn, *gbn;

        len = DH_size(dh);
        bits = DH_bits(dh);
        DH_get0_pqg(dh, &pbn, NULL, &gbn);
        data = app_malloc(len, "print a BN");

        BIO_printf(out, "static DH *get_dh%d(void)\n{\n", bits);
        print_bignum_var(out, pbn, "dhp", bits, data);
        print_bignum_var(out, gbn, "dhg", bits, data);
        BIO_printf(out, "    DH *dh = DH_new();\n"
                        "    BIGNUM *p, *g;\n"
                        "\n"
                        "    if (dh == NULL)\n"
                        "        return NULL;\n");
        BIO_printf(out, "    p = BN_bin2bn(dhp_%d, sizeof(dhp_%d), NULL);\n",
                   bits, bits);
        BIO_printf(out, "    g = BN_bin2bn(dhg_%d, sizeof(dhg_%d), NULL);\n",
                   bits, bits);
        BIO_printf(out, "    if (p == NULL || g == NULL\n"
                        "            || !DH_set0_pqg(dh, p, NULL, g)) {\n"
                        "        DH_free(dh);\n"
                        "        BN_free(p);\n"
                        "        BN_free(g);\n"
                        "        return NULL;\n"
                        "    }\n");
        if (DH_get_length(dh) > 0)
            BIO_printf(out,
                        "    if (!DH_set_length(dh, %ld)) {\n"
                        "        DH_free(dh);\n"
                        "        return NULL;\n"
                        "    }\n", DH_get_length(dh));
        BIO_printf(out, "    return dh;\n}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        const BIGNUM *q;
        DH_get0_pqg(dh, NULL, &q, NULL);
        if (outformat == FORMAT_ASN1) {
            if (q != NULL)
                i = i2d_DHxparams_bio(out, dh);
            else
                i = i2d_DHparams_bio(out, dh);
        } else if (q != NULL) {
            i = PEM_write_bio_DHxparams(out, dh);
        } else {
            i = PEM_write_bio_DHparams(out, dh);
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    BIO_free(in);
    BIO_free_all(out);
    DH_free(dh);
    release_engine(e);
    return ret;
}
Example #20
0
int main(int argc, char *argv[])
	{
	BN_GENCB _cb;
	DH *a;
	DH *b=NULL;
	char buf[12];
	unsigned char *abuf=NULL,*bbuf=NULL;
	int i,alen,blen,aout,bout,ret=1;
	BIO *out;

	CRYPTO_malloc_debug_init();
	CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#ifdef OPENSSL_SYS_WIN32
	CRYPTO_malloc_init();
#endif

	RAND_seed(rnd_seed, sizeof rnd_seed);

	out=BIO_new(BIO_s_file());
	if (out == NULL) EXIT(1);
	BIO_set_fp(out,stdout,BIO_NOCLOSE);

	BN_GENCB_set(&_cb, &cb, out);
	if(((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64,
				DH_GENERATOR_5, &_cb))
		goto err;

	if (!DH_check(a, &i)) goto err;
	if (i & DH_CHECK_P_NOT_PRIME)
		BIO_puts(out, "p value is not prime\n");
	if (i & DH_CHECK_P_NOT_SAFE_PRIME)
		BIO_puts(out, "p value is not a safe prime\n");
	if (i & DH_UNABLE_TO_CHECK_GENERATOR)
		BIO_puts(out, "unable to check the generator value\n");
	if (i & DH_NOT_SUITABLE_GENERATOR)
		BIO_puts(out, "the g value is not a generator\n");

	BIO_puts(out,"\np    =");
	BN_print(out,a->p);
	BIO_puts(out,"\ng    =");
	BN_print(out,a->g);
	BIO_puts(out,"\n");

	b=DH_new();
	if (b == NULL) goto err;

	b->p=BN_dup(a->p);
	b->g=BN_dup(a->g);
	if ((b->p == NULL) || (b->g == NULL)) goto err;

	/* Set a to run with normal modexp and b to use constant time */
	a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME;
	b->flags |= DH_FLAG_NO_EXP_CONSTTIME;

	if (!DH_generate_key(a)) goto err;
	BIO_puts(out,"pri 1=");
	BN_print(out,a->priv_key);
	BIO_puts(out,"\npub 1=");
	BN_print(out,a->pub_key);
	BIO_puts(out,"\n");

	if (!DH_generate_key(b)) goto err;
	BIO_puts(out,"pri 2=");
	BN_print(out,b->priv_key);
	BIO_puts(out,"\npub 2=");
	BN_print(out,b->pub_key);
	BIO_puts(out,"\n");

	alen=DH_size(a);
	abuf=(unsigned char *)OPENSSL_malloc(alen);
	aout=DH_compute_key(abuf,b->pub_key,a);

	BIO_puts(out,"key1 =");
	for (i=0; i<aout; i++)
		{
		snprintf(buf, sizeof(buf), "%02X",abuf[i]);
		BIO_puts(out,buf);
		}
	BIO_puts(out,"\n");

	blen=DH_size(b);
	bbuf=(unsigned char *)OPENSSL_malloc(blen);
	bout=DH_compute_key(bbuf,a->pub_key,b);

	BIO_puts(out,"key2 =");
	for (i=0; i<bout; i++)
		{
		snprintf(buf, sizeof(buf), "%02X",bbuf[i]);
		BIO_puts(out,buf);
		}
	BIO_puts(out,"\n");
	if ((aout < 4) || (bout != aout) || (memcmp(abuf,bbuf,aout) != 0))
		{
		fprintf(stderr,"Error in DH routines\n");
		ret=1;
		}
	else
		ret=0;
err:
	ERR_print_errors_fp(stderr);

	if (abuf != NULL) OPENSSL_free(abuf);
	if (bbuf != NULL) OPENSSL_free(bbuf);
	if(b != NULL) DH_free(b);
	if(a != NULL) DH_free(a);
	BIO_free(out);
#ifdef OPENSSL_SYS_NETWARE
    if (ret) printf("ERROR: %d\n", ret);
#endif
	EXIT(ret);
	return(ret);
	}
Example #21
0
int
gendh_main(int argc, char **argv)
{
	BN_GENCB cb;
	DH *dh = NULL;
	int ret = 1, num = DEFBITS;
	int g = 2;
	char *outfile = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	BIO *out = NULL;

	BN_GENCB_set(&cb, dh_cb, bio_err);

	argv++;
	argc--;
	for (;;) {
		if (argc <= 0)
			break;
		if (strcmp(*argv, "-out") == 0) {
			if (--argc < 1)
				goto bad;
			outfile = *(++argv);
		} else if (strcmp(*argv, "-2") == 0)
			g = 2;
		/*
		 * else if (strcmp(*argv,"-3") == 0) g=3;
		 */
		else if (strcmp(*argv, "-5") == 0)
			g = 5;
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv, "-engine") == 0) {
			if (--argc < 1)
				goto bad;
			engine = *(++argv);
		}
#endif
		else
			break;
		argv++;
		argc--;
	}
	if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) {
bad:
		BIO_printf(bio_err, "usage: gendh [args] [numbits]\n");
		BIO_printf(bio_err, " -out file - output the key to 'file\n");
		BIO_printf(bio_err, " -2        - use 2 as the generator value\n");
		/*
		 * BIO_printf(bio_err," -3        - use 3 as the generator
		 * value\n");
		 */
		BIO_printf(bio_err, " -5        - use 5 as the generator value\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err, " -engine e - use engine e, possibly a hardware device.\n");
#endif
		goto end;
	}
#ifndef OPENSSL_NO_ENGINE
	setup_engine(bio_err, engine, 0);
#endif

	out = BIO_new(BIO_s_file());
	if (out == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, outfile) <= 0) {
			perror(outfile);
			goto end;
		}
	}

	BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, g);
	BIO_printf(bio_err, "This is going to take a long time\n");

	if (((dh = DH_new()) == NULL) || !DH_generate_parameters_ex(dh, num, g, &cb))
		goto end;

	if (!PEM_write_bio_DHparams(out, dh))
		goto end;
	ret = 0;
end:
	if (ret != 0)
		ERR_print_errors(bio_err);
	if (out != NULL)
		BIO_free_all(out);
	if (dh != NULL)
		DH_free(dh);

	return (ret);
}
Example #22
0
int main(int argc, char *argv[])
{
    BN_GENCB *_cb = NULL;
    DH *a = NULL;
    DH *b = NULL;
    BIGNUM *ap = NULL, *ag = NULL, *bp = NULL, *bg = NULL, *apub_key = NULL;
    BIGNUM *bpub_key = NULL, *priv_key = NULL;
    char buf[12] = {0};
    unsigned char *abuf = NULL;
    unsigned char *bbuf = NULL;
    int i, alen, blen, aout, bout;
    int ret = 1;
    BIO *out = NULL;

    CRYPTO_set_mem_debug(1);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    RAND_seed(rnd_seed, sizeof rnd_seed);

    out = BIO_new(BIO_s_file());
    if (out == NULL)
        EXIT(1);
    BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);

    _cb = BN_GENCB_new();
    if (_cb == NULL)
        goto err;
    BN_GENCB_set(_cb, &cb, out);
    if (((a = DH_new()) == NULL)
        || (!DH_generate_parameters_ex(a, 64, DH_GENERATOR_5, _cb)))
        goto err;

    if (!DH_check(a, &i))
        goto err;
    if (i & DH_CHECK_P_NOT_PRIME)
        BIO_puts(out, "p value is not prime\n");
    if (i & DH_CHECK_P_NOT_SAFE_PRIME)
        BIO_puts(out, "p value is not a safe prime\n");
    if (i & DH_UNABLE_TO_CHECK_GENERATOR)
        BIO_puts(out, "unable to check the generator value\n");
    if (i & DH_NOT_SUITABLE_GENERATOR)
        BIO_puts(out, "the g value is not a generator\n");

    DH_get0_pqg(a, &ap, NULL, &ag);
    BIO_puts(out, "\np    =");
    BN_print(out, ap);
    BIO_puts(out, "\ng    =");
    BN_print(out, ag);
    BIO_puts(out, "\n");

    b = DH_new();
    if (b == NULL)
        goto err;

    bp = BN_dup(ap);
    bg = BN_dup(ag);
    if ((bp == NULL) || (bg == NULL) || !DH_set0_pqg(b, bp, NULL, bg))
        goto err;
    bp = bg = NULL;

    if (!DH_generate_key(a))
        goto err;
    DH_get0_key(a, &apub_key, &priv_key);
    BIO_puts(out, "pri 1=");
    BN_print(out, priv_key);
    BIO_puts(out, "\npub 1=");
    BN_print(out, apub_key);
    BIO_puts(out, "\n");

    if (!DH_generate_key(b))
        goto err;
    DH_get0_key(b, &bpub_key, &priv_key);
    BIO_puts(out, "pri 2=");
    BN_print(out, priv_key);
    BIO_puts(out, "\npub 2=");
    BN_print(out, bpub_key);
    BIO_puts(out, "\n");

    alen = DH_size(a);
    abuf = OPENSSL_malloc(alen);
    if (abuf == NULL)
        goto err;

    aout = DH_compute_key(abuf, bpub_key, a);

    BIO_puts(out, "key1 =");
    for (i = 0; i < aout; i++) {
        sprintf(buf, "%02X", abuf[i]);
        BIO_puts(out, buf);
    }
    BIO_puts(out, "\n");

    blen = DH_size(b);
    bbuf = OPENSSL_malloc(blen);
    if (bbuf == NULL)
        goto err;

    bout = DH_compute_key(bbuf, apub_key, b);

    BIO_puts(out, "key2 =");
    for (i = 0; i < bout; i++) {
        sprintf(buf, "%02X", bbuf[i]);
        BIO_puts(out, buf);
    }
    BIO_puts(out, "\n");
    if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) {
        fprintf(stderr, "Error in DH routines\n");
        ret = 1;
    } else
        ret = 0;
    if (!run_rfc5114_tests())
        ret = 1;
 err:
    (void)BIO_flush(out);
    ERR_print_errors_fp(stderr);

    OPENSSL_free(abuf);
    OPENSSL_free(bbuf);
    DH_free(b);
    DH_free(a);
    BN_free(bp);
    BN_free(bg);
    BN_GENCB_free(_cb);
    BIO_free(out);

#ifndef OPENSSL_NO_CRYPTO_MDEBUG
    if (CRYPTO_mem_leaks_fp(stderr) <= 0)
        ret = 1;
#endif

    EXIT(ret);
}
int ssl_test_dsa(int argc, char **argv)
	{
	BN_GENCB cb;
	DSA *dsa=NULL;
	int counter,ret=0,i,j;
	unsigned char buf[256];
	unsigned long h;
	unsigned char sig[256];
	unsigned int siglen;
#ifndef OPENSSL_SYS_WINDOWS
		bio_err = BIO_new(BIO_s_mem());
		if (bio_err == NULL) return(1);
	
#else
		if (bio_err == NULL)
			bio_err=BIO_new_fp(OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE);
#endif


	CRYPTO_malloc_debug_init();
	CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

	ERR_load_crypto_strings();
	RAND_seed(rnd_seed, sizeof rnd_seed);

	TINYCLR_SSL_PRINTF("test generation of DSA parameters\n");

	BN_GENCB_set(&cb, dsa_cb, bio_err);
	if(((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512,
				seed, 20, &counter, &h, &cb))
		goto end;

	TINYCLR_SSL_PRINTF("seed\n");
	for (i=0; i<20; i+=4)
		{
		TINYCLR_SSL_PRINTF("%02X%02X%02X%02X ",
			seed[i],seed[i+1],seed[i+2],seed[i+3]);
		}
	TINYCLR_SSL_PRINTF("\ncounter=%d h=%ld\n",counter,h);
		
	DSA_print(bio_err,dsa,0);
	if (counter != 105) 
		{
		TINYCLR_SSL_PRINTF("counter should be 105\n");
		goto end;
		}
	if (h != 2)
		{
		TINYCLR_SSL_PRINTF("h should be 2\n");
		goto end;
		}

	i=BN_bn2bin(dsa->q,buf);
	j=sizeof(out_q);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_q,i) != 0))
		{
		TINYCLR_SSL_PRINTF("q value is wrong\n");
		goto end;
		}

	i=BN_bn2bin(dsa->p,buf);
	j=sizeof(out_p);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_p,i) != 0))
		{
		TINYCLR_SSL_PRINTF("p value is wrong\n");
		goto end;
		}

	i=BN_bn2bin(dsa->g,buf);
	j=sizeof(out_g);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_g,i) != 0))
		{
		TINYCLR_SSL_PRINTF("g value is wrong\n");
		goto end;
		}

	dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME;
	DSA_generate_key(dsa);
	DSA_sign(0, str1, 20, sig, &siglen, dsa);
	if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
		ret=1;

	dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME;
	DSA_generate_key(dsa);
	DSA_sign(0, str1, 20, sig, &siglen, dsa);
	if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
		ret=1;

end:
	if (!ret)
		ERR_print_errors(bio_err);
	if (dsa != NULL) DSA_free(dsa);
	CRYPTO_cleanup_all_ex_data();
	ERR_remove_thread_state(NULL);
	ERR_free_strings();
	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err = NULL;
		}
#ifdef OPENSSL_SYS_NETWARE
    if (!ret) TINYCLR_SSL_PRINTF("ERROR\n");
#endif
	return(0);
	}
Example #24
0
int MAIN(int argc, char **argv)
	{
	BN_GENCB cb;
	DH *dh=NULL;
	int ret=1,num=DEFBITS;
	int g=2;
	char *outfile=NULL;
	char *inrand=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	BIO *out=NULL;

	apps_startup();

	BN_GENCB_set(&cb, dh_cb, bio_err);
	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto end;

	argv++;
	argc--;
	for (;;)
		{
		if (argc <= 0) break;
		if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (strcmp(*argv,"-2") == 0)
			g=2;
	/*	else if (strcmp(*argv,"-3") == 0)
			g=3; */
		else if (strcmp(*argv,"-5") == 0)
			g=5;
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (strcmp(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			}
		else
			break;
		argv++;
		argc--;
		}
	if ((argc >= 1) && ((sscanf(*argv,"%d",&num) == 0) || (num < 0)))
		{
bad:
		BIO_printf(bio_err,"usage: gendh [args] [numbits]\n");
		BIO_printf(bio_err," -out file - output the key to 'file\n");
		BIO_printf(bio_err," -2        - use 2 as the generator value\n");
	/*	BIO_printf(bio_err," -3        - use 3 as the generator value\n"); */
		BIO_printf(bio_err," -5        - use 5 as the generator value\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e - use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,"           - load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,"             the random number generator\n");
		goto end;
		}
		
#ifndef OPENSSL_NO_ENGINE
        setup_engine(bio_err, engine, 0);
#endif

	out=BIO_new(BIO_s_file());
	if (out == NULL)
		{
		ERR_print_errors(bio_err);
		goto end;
		}

	if (outfile == NULL)
		{
		BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			perror(outfile);
			goto end;
			}
		}

	if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL)
		{
		BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
		}
	if (inrand != NULL)
		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
			app_RAND_load_files(inrand));

	BIO_printf(bio_err,"Generating DH parameters, %d bit long safe prime, generator %d\n",num,g);
	BIO_printf(bio_err,"This is going to take a long time\n");

	if(((dh = DH_new()) == NULL) || !DH_generate_parameters_ex(dh, num, g, &cb))
		goto end;
		
	app_RAND_write_file(NULL, bio_err);

	if (!PEM_write_bio_DHparams(out,dh))
		goto end;
	ret=0;
end:
	if (ret != 0)
		ERR_print_errors(bio_err);
	if (out != NULL) BIO_free_all(out);
	if (dh != NULL) DH_free(dh);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Example #25
0
int MAIN(int argc, char **argv)
	{
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	DSA *dsa=NULL;
	int i,badops=0,text=0;
	BIO *in=NULL,*out=NULL;
	int informat,outformat,noout=0,C=0,ret=1;
	char *infile,*outfile,*prog,*inrand=NULL;
	int numbits= -1,num,genkey=0;
	int need_rand=0;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
#ifdef GENCB_TEST
	int timebomb=0;
#endif

	apps_startup();

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto end;

	infile=NULL;
	outfile=NULL;
	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(strcmp(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if(strcmp(*argv, "-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine = *(++argv);
			}
#endif
#ifdef GENCB_TEST
		else if(strcmp(*argv, "-timebomb") == 0)
			{
			if (--argc < 1) goto bad;
			timebomb = atoi(*(++argv));
			}
#endif
		else if (strcmp(*argv,"-text") == 0)
			text=1;
		else if (strcmp(*argv,"-C") == 0)
			C=1;
		else if (strcmp(*argv,"-genkey") == 0)
			{
			genkey=1;
			need_rand=1;
			}
		else if (strcmp(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			need_rand=1;
			}
		else if (strcmp(*argv,"-noout") == 0)
			noout=1;
		else if (sscanf(*argv,"%d",&num) == 1)
			{
			/* generate a key */
			numbits=num;
			need_rand=1;
			}
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] [bits] <infile >outfile\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -inform arg   input format - DER or PEM\n");
		BIO_printf(bio_err," -outform arg  output format - DER or PEM\n");
		BIO_printf(bio_err," -in arg       input file\n");
		BIO_printf(bio_err," -out arg      output file\n");
		BIO_printf(bio_err," -text         print as text\n");
		BIO_printf(bio_err," -C            Output C code\n");
		BIO_printf(bio_err," -noout        no output\n");
		BIO_printf(bio_err," -genkey       generate a DSA key\n");
		BIO_printf(bio_err," -rand         files to use for random number input\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e     use engine e, possibly a hardware device.\n");
#endif
#ifdef GENCB_TEST
		BIO_printf(bio_err," -timebomb n   interrupt keygen after <n> seconds\n");
#endif
		BIO_printf(bio_err," number        number of bits to use for generating private key\n");
		goto end;
		}

	ERR_load_crypto_strings();

	in=BIO_new(BIO_s_file());
	out=BIO_new(BIO_s_file());
	if ((in == NULL) || (out == NULL))
		{
		ERR_print_errors(bio_err);
		goto end;
		}

	if (infile == NULL)
		BIO_set_fp(in,stdin,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			perror(infile);
			goto end;
			}
		}
	if (outfile == NULL)
		{
		BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			perror(outfile);
			goto end;
			}
		}

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if (need_rand)
		{
		app_RAND_load_file(NULL, bio_err, (inrand != NULL));
		if (inrand != NULL)
			BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
				app_RAND_load_files(inrand));
		}

	if (numbits > 0)
		{
		BN_GENCB cb;
		BN_GENCB_set(&cb, dsa_cb, bio_err);
		assert(need_rand);
		dsa = DSA_new();
		if(!dsa)
			{
			BIO_printf(bio_err,"Error allocating DSA object\n");
			goto end;
			}
		BIO_printf(bio_err,"Generating DSA parameters, %d bit long prime\n",num);
	        BIO_printf(bio_err,"This could take some time\n");
#ifdef GENCB_TEST
		if(timebomb > 0)
	{
		struct sigaction act;
		act.sa_handler = timebomb_sigalarm;
		act.sa_flags = 0;
		BIO_printf(bio_err,"(though I'll stop it if not done within %d secs)\n",
				timebomb);
		if(sigaction(SIGALRM, &act, NULL) != 0)
			{
			BIO_printf(bio_err,"Error, couldn't set SIGALRM handler\n");
			goto end;
			}
		alarm(timebomb);
	}
#endif
	        if(!DSA_generate_parameters_ex(dsa,num,NULL,0,NULL,NULL, &cb))
			{
#ifdef GENCB_TEST
			if(stop_keygen_flag)
				{
				BIO_printf(bio_err,"DSA key generation time-stopped\n");
				/* This is an asked-for behaviour! */
				ret = 0;
				goto end;
				}
#endif
			BIO_printf(bio_err,"Error, DSA key generation failed\n");
			goto end;
			}
		}
	else if	(informat == FORMAT_ASN1)
		dsa=d2i_DSAparams_bio(in,NULL);
	else if (informat == FORMAT_PEM)
		dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL);
	else
		{
		BIO_printf(bio_err,"bad input format specified\n");
		goto end;
		}
	if (dsa == NULL)
		{
		BIO_printf(bio_err,"unable to load DSA parameters\n");
		ERR_print_errors(bio_err);
		goto end;
		}

	if (text)
		{
		DSAparams_print(out,dsa);
		}
	
	if (C)
		{
		unsigned char *data;
		int l,len,bits_p,bits_q,bits_g;

		len=BN_num_bytes(dsa->p);
		bits_p=BN_num_bits(dsa->p);
		bits_q=BN_num_bits(dsa->q);
		bits_g=BN_num_bits(dsa->g);
		data=(unsigned char *)OPENSSL_malloc(len+20);
		if (data == NULL)
			{
			perror("OPENSSL_malloc");
			goto end;
			}
		l=BN_bn2bin(dsa->p,data);
		printf("static unsigned char dsa%d_p[]={",bits_p);
		for (i=0; i<l; i++)
			{
			if ((i%12) == 0) printf("\n\t");
			printf("0x%02X,",data[i]);
			}
		printf("\n\t};\n");

		l=BN_bn2bin(dsa->q,data);
		printf("static unsigned char dsa%d_q[]={",bits_p);
		for (i=0; i<l; i++)
			{
			if ((i%12) == 0) printf("\n\t");
			printf("0x%02X,",data[i]);
			}
		printf("\n\t};\n");

		l=BN_bn2bin(dsa->g,data);
		printf("static unsigned char dsa%d_g[]={",bits_p);
		for (i=0; i<l; i++)
			{
			if ((i%12) == 0) printf("\n\t");
			printf("0x%02X,",data[i]);
			}
		printf("\n\t};\n\n");

		printf("DSA *get_dsa%d()\n\t{\n",bits_p);
		printf("\tDSA *dsa;\n\n");
		printf("\tif ((dsa=DSA_new()) == NULL) return(NULL);\n");
		printf("\tdsa->p=BN_bin2bn(dsa%d_p,sizeof(dsa%d_p),NULL);\n",
			bits_p,bits_p);
		printf("\tdsa->q=BN_bin2bn(dsa%d_q,sizeof(dsa%d_q),NULL);\n",
			bits_p,bits_p);
		printf("\tdsa->g=BN_bin2bn(dsa%d_g,sizeof(dsa%d_g),NULL);\n",
			bits_p,bits_p);
		printf("\tif ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))\n");
		printf("\t\t{ DSA_free(dsa); return(NULL); }\n");
		printf("\treturn(dsa);\n\t}\n");
		}


	if (!noout)
		{
		if 	(outformat == FORMAT_ASN1)
			i=i2d_DSAparams_bio(out,dsa);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_DSAparams(out,dsa);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		if (!i)
			{
			BIO_printf(bio_err,"unable to write DSA parameters\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		}
	if (genkey)
		{
		DSA *dsakey;

		assert(need_rand);
		if ((dsakey=DSAparams_dup(dsa)) == NULL) goto end;
		if (!DSA_generate_key(dsakey)) goto end;
		if 	(outformat == FORMAT_ASN1)
			i=i2d_DSAPrivateKey_bio(out,dsakey);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_DSAPrivateKey(out,dsakey,NULL,NULL,0,NULL,NULL);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		DSA_free(dsakey);
		}
	if (need_rand)
		app_RAND_write_file(NULL, bio_err);
	ret=0;
end:
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (dsa != NULL) DSA_free(dsa);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Example #26
0
/* "translation callback" to call EVP_PKEY_CTX callbacks using BN_GENCB
 * style callbacks.
 */

static int trans_cb(int a, int b, BN_GENCB *gcb)
	{
	EVP_PKEY_CTX *ctx = gcb->arg;
	ctx->keygen_info[0] = a;
	ctx->keygen_info[1] = b;
	return ctx->pkey_gencb(ctx);
	}	

void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx)
	{
	BN_GENCB_set(cb, trans_cb, ctx)
	}

int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx)
	{
	if (idx == -1)
		return ctx->keygen_info_count; 
	if (idx < 0 || idx > ctx->keygen_info_count)
		return 0;
	return ctx->keygen_info[idx];
	}

EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e,
				unsigned char *key, int keylen)
	{
	EVP_PKEY_CTX *mac_ctx = NULL;
Example #27
0
static isc_result_t
opensslrsa_generate(dst_key_t *key, int exp, void (*callback)(int)) {
#if OPENSSL_VERSION_NUMBER > 0x00908000L
	isc_result_t ret = DST_R_OPENSSLFAILURE;
	BN_GENCB cb;
	union {
		void *dptr;
		void (*fptr)(int);
	} u;
	RSA *rsa = RSA_new();
	BIGNUM *e = BN_new();
#if USE_EVP
	EVP_PKEY *pkey = EVP_PKEY_new();
#endif

	if (rsa == NULL || e == NULL)
		goto err;
#if USE_EVP
	if (pkey == NULL)
		goto err;
	if (!EVP_PKEY_set1_RSA(pkey, rsa))
		goto err;
#endif

	if (exp == 0) {
		/* RSA_F4 0x10001 */
		BN_set_bit(e, 0);
		BN_set_bit(e, 16);
	} else {
		/* F5 0x100000001 */
		BN_set_bit(e, 0);
		BN_set_bit(e, 32);
	}

	if (callback == NULL) {
		BN_GENCB_set_old(&cb, NULL, NULL);
	} else {
		u.fptr = callback;
		BN_GENCB_set(&cb, &progress_cb, u.dptr);
	}

	if (RSA_generate_key_ex(rsa, key->key_size, e, &cb)) {
		BN_free(e);
		SET_FLAGS(rsa);
#if USE_EVP
		key->keydata.pkey = pkey;

		RSA_free(rsa);
#else
		key->keydata.rsa = rsa;
#endif
		return (ISC_R_SUCCESS);
	}
	ret = dst__openssl_toresult2("RSA_generate_key_ex",
				     DST_R_OPENSSLFAILURE);

err:
#if USE_EVP
	if (pkey != NULL)
		EVP_PKEY_free(pkey);
#endif
	if (e != NULL)
		BN_free(e);
	if (rsa != NULL)
		RSA_free(rsa);
	return (dst__openssl_toresult(ret));
#else
	RSA *rsa;
	unsigned long e;
#if USE_EVP
	EVP_PKEY *pkey = EVP_PKEY_new();

	UNUSED(callback);

	if (pkey == NULL)
		return (ISC_R_NOMEMORY);
#else
	UNUSED(callback);
#endif

	if (exp == 0)
	       e = RSA_F4;
	else
	       e = 0x40000003;
	rsa = RSA_generate_key(key->key_size, e, NULL, NULL);
	if (rsa == NULL) {
#if USE_EVP
		EVP_PKEY_free(pkey);
#endif
		return (dst__openssl_toresult2("RSA_generate_key",
					       DST_R_OPENSSLFAILURE));
	}
	SET_FLAGS(rsa);
#if USE_EVP
	if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
		EVP_PKEY_free(pkey);
		RSA_free(rsa);
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
	}
	key->keydata.pkey = pkey;
	RSA_free(rsa);
#else
	key->keydata.rsa = rsa;
#endif

	return (ISC_R_SUCCESS);
#endif
}
Example #28
0
File: tincd.c Project: seehuhn/tinc
/*
  Generate a public/private RSA keypair, and ask for a file to store
  them in.
*/
static bool keygen(int bits) {
	BIGNUM *e = NULL;
	RSA *rsa_key;
	FILE *f;
	char filename[PATH_MAX];
	BN_GENCB *cb;
	int result;

	fprintf(stderr, "Generating %d bits keys:\n", bits);

	cb = BN_GENCB_new();

	if(!cb) {
		abort();
	}

	BN_GENCB_set(cb, indicator, NULL);

	rsa_key = RSA_new();

	if(BN_hex2bn(&e, "10001") == 0) {
		abort();
	}

	if(!rsa_key || !e) {
		abort();
	}

	result = RSA_generate_key_ex(rsa_key, bits, e, cb);

	BN_free(e);
	BN_GENCB_free(cb);

	if(!result) {
		fprintf(stderr, "Error during key generation!\n");
		RSA_free(rsa_key);
		return false;
	} else {
		fprintf(stderr, "Done.\n");
	}

	snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
	f = ask_and_open(filename, "private RSA key");

	if(!f) {
		RSA_free(rsa_key);
		return false;
	}

#ifdef HAVE_FCHMOD
	/* Make it unreadable for others. */
	fchmod(fileno(f), 0600);
#endif

	fputc('\n', f);
	PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
	fclose(f);

	char *name = get_name();

	if(name) {
		snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
		free(name);
	} else {
		snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
	}

	f = ask_and_open(filename, "public RSA key");

	if(!f) {
		RSA_free(rsa_key);
		return false;
	}

	fputc('\n', f);
	PEM_write_RSAPublicKey(f, rsa_key);
	fclose(f);

	RSA_free(rsa_key);

	return true;
}
int MAIN(int argc, char **argv)
	{
	BN_GENCB cb;
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	int ret=1;
	int i,num=DEFBITS;
	long l;
	const EVP_CIPHER *enc=NULL;
	unsigned long f4=RSA_F4;
	char *outfile=NULL;
	char *passargout = NULL, *passout = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	char *inrand=NULL;
	BIO *out=NULL;
	BIGNUM *bn = BN_new();
	RSA *rsa = NULL;

	if(!bn) goto err;

	apps_startup();
	BN_GENCB_set(&cb, genrsa_cb, bio_err);

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto err;
	if ((out=BIO_new(BIO_s_file())) == NULL)
		{
		BIO_printf(bio_err,"unable to create BIO for output\n");
		goto err;
		}

	argv++;
	argc--;
	for (;;)
		{
		if (argc <= 0) break;
		if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-3") == 0)
			f4=3;
		else if (TINYCLR_SSL_STRCMP(*argv,"-F4") == 0 || TINYCLR_SSL_STRCMP(*argv,"-f4") == 0)
			f4=RSA_F4;
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			}
#ifndef OPENSSL_NO_DES
		else if (TINYCLR_SSL_STRCMP(*argv,"-des") == 0)
			enc=EVP_des_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-des3") == 0)
			enc=EVP_des_ede3_cbc();
#endif
#ifndef OPENSSL_NO_IDEA
		else if (TINYCLR_SSL_STRCMP(*argv,"-idea") == 0)
			enc=EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
		else if (TINYCLR_SSL_STRCMP(*argv,"-seed") == 0)
			enc=EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes128") == 0)
			enc=EVP_aes_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes192") == 0)
			enc=EVP_aes_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes256") == 0)
			enc=EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia128") == 0)
			enc=EVP_camellia_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia192") == 0)
			enc=EVP_camellia_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia256") == 0)
			enc=EVP_camellia_256_cbc();
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
		else
			break;
		argv++;
		argc--;
		}
	if ((argc >= 1) && ((sscanf(*argv,"%d",&num) == 0) || (num < 0)))
		{
bad:
		BIO_printf(bio_err,"usage: genrsa [args] [numbits]\n");
		BIO_printf(bio_err," -des            encrypt the generated key with DES in cbc mode\n");
		BIO_printf(bio_err," -des3           encrypt the generated key with DES in ede cbc mode (168 bit key)\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err," -idea           encrypt the generated key with IDEA in cbc mode\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err," -seed\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err," -aes128, -aes192, -aes256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err," -out file       output the key to 'file\n");
		BIO_printf(bio_err," -passout arg    output file pass phrase source\n");
		BIO_printf(bio_err," -f4             use F4 (0x10001) for the E value\n");
		BIO_printf(bio_err," -3              use 3 for the E value\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,"                 load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,"                 the random number generator\n");
		goto err;
		}
		
	ERR_load_crypto_strings();

	if(!app_passwd(bio_err, NULL, passargout, NULL, &passout)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto err;
	}

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto err;
			}
		}

	if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
		&& !RAND_status())
		{
		BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
		}
	if (inrand != NULL)
		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
			app_RAND_load_files(inrand));

	BIO_printf(bio_err,"Generating RSA private key, %d bit long modulus\n",
		num);
#ifdef OPENSSL_NO_ENGINE
	rsa = RSA_new();
#else
	rsa = RSA_new_method(e);
#endif
	if (!rsa)
		goto err;

	if(!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb))
		goto err;
		
	app_RAND_write_file(NULL, bio_err);

	/* We need to do the following for when the base number size is <
	 * long, esp windows 3.1 :-(. */
	l=0L;
	for (i=0; i<rsa->e->top; i++)
		{
#ifndef SIXTY_FOUR_BIT
		l<<=BN_BITS4;
		l<<=BN_BITS4;
#endif
		l+=rsa->e->d[i];
		}
	BIO_printf(bio_err,"e is %ld (0x%lX)\n",l,l);
	{
	PW_CB_DATA cb_data;
	cb_data.password = passout;
	cb_data.prompt_info = outfile;
	if (!PEM_write_bio_RSAPrivateKey(out,rsa,enc,NULL,0,
		(pem_password_cb *)password_callback,&cb_data))
		goto err;
	}

	ret=0;
err:
	if (bn) BN_free(bn);
	if (rsa) RSA_free(rsa);
	if (out) BIO_free_all(out);
	if(passout) OPENSSL_free(passout);
	if (ret != 0)
		ERR_print_errors(bio_err);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Example #30
0
static isc_result_t
openssldh_generate(dst_key_t *key, int generator, void (*callback)(int)) {
	DH *dh = NULL;
#if OPENSSL_VERSION_NUMBER > 0x00908000L
	BN_GENCB *cb;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	BN_GENCB _cb;
#endif
	union {
		void *dptr;
		void (*fptr)(int);
	} u;
#else

	UNUSED(callback);
#endif

	if (generator == 0) {
		if (key->key_size == 768 ||
		    key->key_size == 1024 ||
		    key->key_size == 1536)
		{
			dh = DH_new();
			if (dh == NULL)
				return (dst__openssl_toresult(ISC_R_NOMEMORY));
			if (key->key_size == 768)
				dh->p = bn768;
			else if (key->key_size == 1024)
				dh->p = bn1024;
			else
				dh->p = bn1536;
			dh->g = bn2;
		} else
			generator = 2;
	}

	if (generator != 0) {
#if OPENSSL_VERSION_NUMBER > 0x00908000L
		dh = DH_new();
		if (dh == NULL)
			return (dst__openssl_toresult(ISC_R_NOMEMORY));
		cb = BN_GENCB_new();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
		if (cb == NULL) {
			DH_free(dh);
			return (dst__openssl_toresult(ISC_R_NOMEMORY));
		}
#endif
		if (callback == NULL) {
			BN_GENCB_set_old(cb, NULL, NULL);
		} else {
			u.fptr = callback;
			BN_GENCB_set(cb, &progress_cb, u.dptr);
		}

		if (!DH_generate_parameters_ex(dh, key->key_size, generator,
					       cb)) {
			DH_free(dh);
			BN_GENCB_free(cb);
			return (dst__openssl_toresult2(
					"DH_generate_parameters_ex",
					DST_R_OPENSSLFAILURE));
		}
		BN_GENCB_free(cb);
#else
		dh = DH_generate_parameters(key->key_size, generator,
					    NULL, NULL);
		if (dh == NULL)
			return (dst__openssl_toresult2(
					"DH_generate_parameters",
					DST_R_OPENSSLFAILURE));
#endif
	}

	if (DH_generate_key(dh) == 0) {
		DH_free(dh);
		return (dst__openssl_toresult2("DH_generate_key",
					       DST_R_OPENSSLFAILURE));
	}
	dh->flags &= ~DH_FLAG_CACHE_MONT_P;

	key->keydata.dh = dh;

	return (ISC_R_SUCCESS);
}