예제 #1
0
dsa160_key::dsa160_key(int bits)
{
    if (bits == 0) {
        bits = 2048;
    }
    // Choose an appropriate set of DSA parameters for the new key.
    if (bits <= 1024) {
        dsa_ = get_dsa1024();
    }
    else if (bits <= 2048) {
        dsa_ = get_dsa2048();
    }
    else if (bits <= 3072) {
        dsa_ = get_dsa3072();
    }
    else {
        logger::fatal() << "Can't currently produce DSA keys with more than 3072 bits";
    }

    assert(dsa_);

    // Generate a new DSA key given those parameters
    int rc = DSA_generate_key(dsa_);
    assert(rc == 1);
    assert(dsa_->priv_key != nullptr);
    if (rc != 1 or dsa_->priv_key == nullptr) {
        throw std::runtime_error("Cannot generate DSA private key");
    }

    set_type(public_and_private);
}
예제 #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);
}
예제 #3
0
int crypto_sign_keypair(unsigned char *pk,unsigned char *sk)
{
  DSA *x;
  int len;

  x = DSA_new();
  if (!x) return -1;

  memset(sk,0,SECRETKEY_BYTES);
  memset(pk,0,PUBLICKEY_BYTES);

  x->p = BN_new(); if (!x->p) goto error;
  x->q = BN_new(); if (!x->q) goto error;
  x->g = BN_new(); if (!x->g) goto error;

  if (!BN_bin2bn(prime,sizeof prime,x->p)) goto error;
  if (!BN_bin2bn(prime_q,sizeof prime_q,x->q)) goto error;
  if (!BN_bin2bn(prime_g,sizeof prime_g,x->g)) goto error;

  if (!DSA_generate_key(x)) goto error;

  len = BN_num_bytes(x->pub_key); if (len > PUBLICKEY_BYTES) goto error;
  BN_bn2bin(x->pub_key,pk + PUBLICKEY_BYTES - len);
  BN_bn2bin(x->pub_key,sk + PUBLICKEY_BYTES - len);

  len = BN_num_bytes(x->priv_key); if (len > SECRETKEY_BYTES - PUBLICKEY_BYTES) goto error;
  BN_bn2bin(x->priv_key,sk + SECRETKEY_BYTES - len);

  DSA_free(x);
  return 0;

error:
  DSA_free(x);
  return -1;
}
예제 #4
0
void openssl_dsa_crypt()
{
	DSA *d;
	unsigned int size, len;
	unsigned char inputs[COMM_LEN] = "dsa crypt";
	unsigned char outputs[MAX1_LEN] = { 0 };

	printf("\nDSA generate key:\n");
	d = DSA_new();
	DSA_generate_parameters_ex(d, LINE_LEN, NULL, 0, NULL, NULL, NULL);
	DSA_generate_key(d);
	DSA_print_fp(stdout, d, 0);
	
	DSA_sign(NID_md5_sha1, inputs, 20, outputs, &len, d);
	printf("DSA_sign(%s) = ", inputs);
	for (size = 0; size < len; size++)
		printf("%.02x", outputs[size]);
	printf("\n");
	
	DSA_verify(NID_md5_sha1, inputs, 20, outputs, len, d);
	printf("DSA_verify(");
	for (size = 0; size < len; size++)
		printf("%.02x", outputs[size]);
	printf(") = %s\n", inputs);
	
	DSA_free(d);
}
void keypair()
    {
    char buf[1024];
    int nmod=0;

    while(fgets(buf,sizeof buf,stdin) != NULL)
	{
	if(!strncmp(buf,"[mod = ",7))
	    nmod=atoi(buf+7);
	else if(!strncmp(buf,"N = ",4))
	    {
	    DSA *dsa;
	    int n=atoi(buf+4);

	    printf("[mod = %d]\n\n",nmod);

	    dsa=DSA_generate_parameters(nmod,NULL,0,NULL,NULL,NULL,NULL);
	    pbn("P",dsa->p);
	    pbn("Q",dsa->q);
	    pbn("G",dsa->g);
	    putc('\n',stdout);

	    while(n--)
		{
		DSA_generate_key(dsa);

		pbn("X",dsa->priv_key);
		pbn("Y",dsa->pub_key);
		putc('\n',stdout);
		}
	    }
	}
    }
예제 #6
0
static EP_STAT
generate_dsa_key(EP_CRYPTO_KEY *key, int keylen)
{
	DSA *dsakey;

	// generate new parameter block
	dsakey = DSA_new();
	if (DSA_generate_parameters_ex(dsakey, keylen,
			NULL, 0, NULL, NULL, NULL) != 1)
	{
		_ep_crypto_error("cannot initialize DSA parameters");
		goto fail0;
	}

	if (DSA_generate_key(dsakey) != 1)
	{
		_ep_crypto_error("cannot generate DSA key");
		goto fail0;
	}
	if (EVP_PKEY_assign_DSA(key, dsakey) != 1)
	{
		_ep_crypto_error("cannot save DSA key");
		goto fail0;
	}

	return EP_STAT_OK;

fail0:
	return EP_STAT_CRYPTO_KEYCREATE;
}
static void keypair(FILE *in, FILE *out)
    {
    char buf[1024];
    char lbuf[1024];
    char *keyword, *value;
    int dsa2, L, N;

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		continue;
		}
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, NULL))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    fputs(buf,out);
	    }
	else if(!strcmp(keyword,"N"))
	    {
	    DSA *dsa;
	    int n=atoi(value);

	    dsa = FIPS_dsa_new();
	    if (!dsa2 && !dsa_builtin_paramgen(dsa, L, N, NULL, NULL, 0,
						NULL, NULL, NULL, NULL))
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    if (dsa2 && dsa_builtin_paramgen2(dsa, L, N, NULL, NULL, 0, -1,
						NULL, NULL, NULL, NULL) <= 0)
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    do_bn_print_name(out, "P",dsa->p);
	    do_bn_print_name(out, "Q",dsa->q);
	    do_bn_print_name(out, "G",dsa->g);
	    fputs(RESP_EOL, out);

	    while(n--)
		{
		if (!DSA_generate_key(dsa))
			exit(1);

		do_bn_print_name(out, "X",dsa->priv_key);
		do_bn_print_name(out, "Y",dsa->pub_key);
	    	fputs(RESP_EOL, out);
		}
	    if (dsa)
		FIPS_dsa_free(dsa);
	    }
	}
    }
예제 #8
0
// Key factory
bool OSSLDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */)
{
	// Check parameters
	if ((ppKeyPair == NULL) ||
	    (parameters == NULL))
	{
		return false;
	}

	if (!parameters->areOfType(DSAParameters::type))
	{
		ERROR_MSG("Invalid parameters supplied for DSA key generation");

		return false;
	}

	DSAParameters* params = (DSAParameters*) parameters;

	// Generate the key-pair
	DSA* dsa = DSA_new();

	if (dsa == NULL)
	{
		ERROR_MSG("Failed to instantiate OpenSSL DSA object");

		return false;
	}

	// Use the OpenSSL implementation and not any engine
	DSA_set_method(dsa, DSA_get_default_method());

	dsa->p = OSSL::byteString2bn(params->getP());
	dsa->q = OSSL::byteString2bn(params->getQ());
	dsa->g = OSSL::byteString2bn(params->getG());

	if (DSA_generate_key(dsa) != 1)
	{
		ERROR_MSG("DSA key generation failed (0x%08X)", ERR_get_error());

		DSA_free(dsa);

		return false;
	}

	// Create an asymmetric key-pair object to return
	OSSLDSAKeyPair* kp = new OSSLDSAKeyPair();

	((OSSLDSAPublicKey*) kp->getPublicKey())->setFromOSSL(dsa);
	((OSSLDSAPrivateKey*) kp->getPrivateKey())->setFromOSSL(dsa);

	*ppKeyPair = kp;

	// Release the key
	DSA_free(dsa);

	return true;
}
static int genkeys(void)
{
    if (!TEST_ptr(dsakey = load_dsa_params()))
        return 0;

    if (!TEST_int_eq(DSA_generate_key(dsakey), 1))
        return 0;

    return 1;
}
예제 #10
0
int main(int argc, char **argv)
{
    DSA *dsa;
    unsigned char*  input_string;
    unsigned char*  sign_string;
    unsigned int    sig_len;
    unsigned int    i;

    if ( argc != 2 )
    {
        fprintf(stderr, "%s <plain text>\n", argv[0]);
        exit(-1);
    }

    input_string = (unsigned char*)calloc(strlen(argv[1]) + 1, sizeof(unsigned char));
    if ( input_string == NULL )
    {
        fprintf(stderr, "Unable to allocate memory for input_string\n");
        exit(-1);
    }
    strncpy((char *)input_string, argv[1], strlen(argv[1]));

    dsa = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, NULL, NULL);

    DSA_generate_key(dsa);

    sign_string = (unsigned char *)calloc(DSA_size(dsa), sizeof(unsigned char));
    if ( sign_string == NULL )
    {
        fprintf(stderr, "Unable to allocate memory for sign_string\n");
        exit(-1);
    }

    if ( DSA_sign(0, input_string, strlen((char *)input_string), sign_string, &sig_len, dsa) == 0 )
    {
        fprintf(stderr, "Sign error\n");
        exit(-1);
    }

    int is_valid_signature = DSA_verify(0, input_string, strlen((char*)input_string), sign_string, sig_len, dsa);

    DSAparams_print_fp(stdout, dsa);
    printf("input_string = %s\n", input_string);
    printf("signed string = ");
    for ( i = 0; i < sig_len; i++ )
        printf("%x%x", (sign_string[i] >> 4) & 0xf, sign_string[i] & 0xf);
    printf("\n");
    printf("is_valid_signature? = %d\n", is_valid_signature);

    return 0;
}
예제 #11
0
파일: keygenDSA.c 프로젝트: oplol/univ-code
int main()
{
   DSA *key;
   FILE *fp1, *fp2;
   unsigned char digest[8] = "1234567";
   int siglen;
   unsigned char signature[1000];
   int retcode;

   key = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, NULL, NULL);

   if (key == NULL)
   {
      printf("\nFailed to generate parameters\n");
      exit(1);
   }
   fp1 = fopen("params.dat", "w");
   DSAparams_print_fp(fp1, key);
   fclose(fp1);

   DSA_generate_key(key);
   if (key == NULL)
   {
      printf("\nFailed to generate key\n");
      exit(1);
   }

   fp2 = fopen("key.dat", "w");

   DSA_print_fp(fp2, key, 0);
   fclose(fp2);

   retcode = DSA_sign(0, digest, 8, signature, &siglen, key);
   if (retcode == 0)
   {
      printf("\n *** Error in signing ***\n\n");
      exit(1);
   }
   printf("\n%s\n",signature);

   retcode = DSA_verify(0, digest, 8, signature, siglen, key);
   if (retcode == 1)
      printf("\n *** Valid signature ***\n\n");
   if (retcode == 0)
      printf("\n *** Incorrect signature ***\n\n");
   if (retcode == -1)
      printf("\n *** Error in verifying ***\n\n");

   DSA_free(key);
   return 0;
}
예제 #12
0
파일: dsatest.c 프로젝트: Vonage/openssl
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;
}
예제 #13
0
파일: pki_evp.cpp 프로젝트: J-Javan/xca
void pki_evp::generate(int bits, int type, QProgressBar *progress, int curve_nid)
{
	RSA *rsakey;
	DSA *dsakey;
	EC_KEY *eckey;

	progress->setMinimum(0);
	progress->setMaximum(100);
	progress->setValue(50);

	switch (type) {
	case EVP_PKEY_RSA:
		rsakey = RSA_generate_key(bits, 0x10001, inc_progress_bar,
			progress);
		if (rsakey)
			EVP_PKEY_assign_RSA(key, rsakey);
		break;
	case EVP_PKEY_DSA:
		progress->setMaximum(500);
		dsakey = DSA_generate_parameters(bits, NULL, 0, NULL, NULL,
				inc_progress_bar, progress);
		DSA_generate_key(dsakey);
		if (dsakey)
			EVP_PKEY_assign_DSA(key, dsakey);
		break;
	case EVP_PKEY_EC:
		EC_GROUP *group = EC_GROUP_new_by_curve_name(curve_nid);
		if (!group)
			break;
		eckey = EC_KEY_new();
		if (eckey == NULL) {
			EC_GROUP_free(group);
			break;
		}
		EC_GROUP_set_asn1_flag(group, 1);
		if (EC_KEY_set_group(eckey, group)) {
			if (EC_KEY_generate_key(eckey)) {
				EVP_PKEY_assign_EC_KEY(key, eckey);
				EC_GROUP_free(group);
				break;
			}
		}
		EC_KEY_free(eckey);
		EC_GROUP_free(group);
		break;
	}
	pki_openssl_error();
	encryptKey();
}
static int generate_dsa_keypair(EVP_PKEY* pkey, const keymaster_dsa_keygen_params_t* dsa_params) {
    if (dsa_params->key_size < 512) {
        ALOGI("Requested DSA key size is too small (<512)");
        return -1;
    }

    Unique_DSA dsa(DSA_new());

    if (dsa_params->generator_len == 0 || dsa_params->prime_p_len == 0 ||
        dsa_params->prime_q_len == 0 || dsa_params->generator == NULL ||
        dsa_params->prime_p == NULL || dsa_params->prime_q == NULL) {
        if (DSA_generate_parameters_ex(dsa.get(), dsa_params->key_size, NULL, 0, NULL, NULL,
                                       NULL) != 1) {
            logOpenSSLError("generate_dsa_keypair");
            return -1;
        }
    } else {
        dsa->g = BN_bin2bn(dsa_params->generator, dsa_params->generator_len, NULL);
        if (dsa->g == NULL) {
            logOpenSSLError("generate_dsa_keypair");
            return -1;
        }

        dsa->p = BN_bin2bn(dsa_params->prime_p, dsa_params->prime_p_len, NULL);
        if (dsa->p == NULL) {
            logOpenSSLError("generate_dsa_keypair");
            return -1;
        }

        dsa->q = BN_bin2bn(dsa_params->prime_q, dsa_params->prime_q_len, NULL);
        if (dsa->q == NULL) {
            logOpenSSLError("generate_dsa_keypair");
            return -1;
        }
    }

    if (DSA_generate_key(dsa.get()) != 1) {
        logOpenSSLError("generate_dsa_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_DSA(pkey, dsa.get()) == 0) {
        logOpenSSLError("generate_dsa_keypair");
        return -1;
    }
    release_because_ownership_transferred(dsa);

    return 0;
}
예제 #15
0
static isc_result_t
openssldsa_generate(dst_key_t *key, int unused) {
#if OPENSSL_VERSION_NUMBER > 0x00908000L
        BN_GENCB cb;
#endif
	DSA *dsa;
	unsigned char rand_array[ISC_SHA1_DIGESTLENGTH];
	isc_result_t result;

	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));

	BN_GENCB_set_old(&cb, NULL, NULL);
  
	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->opaque = dsa;

	return (ISC_R_SUCCESS);
}
예제 #16
0
static int pkey_dsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
    DSA *dsa = NULL;
    if (ctx->pkey == NULL) {
        DSAerr(DSA_F_PKEY_DSA_KEYGEN, DSA_R_NO_PARAMETERS_SET);
        return 0;
    }
    dsa = DSA_new();
    if (dsa == NULL)
        return 0;
    EVP_PKEY_assign_DSA(pkey, dsa);
    /* Note: if error return, pkey is freed by parent routine */
    if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey))
        return 0;
    return DSA_generate_key(pkey->pkey.dsa);
}
예제 #17
0
/*
 * DSA: generate keys and sign, verify input plaintext.
 */
static int FIPS_dsa_test(int bad)
{
    DSA *dsa = NULL;
    EVP_PKEY pk;
    unsigned char dgst[] = "etaonrishdlc";
    unsigned char buf[60];
    unsigned int slen;
    int r = 0;
    EVP_MD_CTX mctx;

    ERR_clear_error();
    EVP_MD_CTX_init(&mctx);
    dsa = DSA_new();
    if (!dsa)
        goto end;
    if (!DSA_generate_parameters_ex(dsa, 1024, NULL, 0, NULL, NULL, NULL))
        goto end;
    if (!DSA_generate_key(dsa))
        goto end;
    if (bad)
        BN_add_word(dsa->pub_key, 1);

    pk.type = EVP_PKEY_DSA;
    pk.pkey.dsa = dsa;

    if (!EVP_SignInit_ex(&mctx, EVP_dss1(), NULL))
        goto end;
    if (!EVP_SignUpdate(&mctx, dgst, sizeof(dgst) - 1))
        goto end;
    if (!EVP_SignFinal(&mctx, buf, &slen, &pk))
        goto end;

    if (!EVP_VerifyInit_ex(&mctx, EVP_dss1(), NULL))
        goto end;
    if (!EVP_VerifyUpdate(&mctx, dgst, sizeof(dgst) - 1))
        goto end;
    r = EVP_VerifyFinal(&mctx, buf, slen, &pk);
end:
    EVP_MD_CTX_cleanup(&mctx);
    if (dsa)
        DSA_free(dsa);
    if (r != 1)
        return 0;
    return 1;
}
예제 #18
0
int32_t CryptoNative_DsaGenerateKey(DSA** dsa, int32_t bits)
{
    *dsa = DSA_new();
    if (!dsa)
    {
        assert(false);
        return 0;
    }

    if (!DSA_generate_parameters_ex(*dsa, bits, NULL, 0, NULL, NULL, NULL) ||
        !DSA_generate_key(*dsa))
    {
        DSA_free(*dsa);
        *dsa = NULL;
        return 0;
    }

    return 1;
}
예제 #19
0
/*
 * DSA: generate keys and sign, verify input plaintext.
 */
static int FIPS_dsa_test(int bad)
{
    DSA *dsa = NULL;
    unsigned char dgst[] = "etaonrishdlc";
    int r = 0;
    EVP_MD_CTX mctx;
    DSA_SIG *sig = NULL;

    ERR_clear_error();
    FIPS_md_ctx_init(&mctx);
    dsa = FIPS_dsa_new();
    if (!dsa)
        goto end;
    if (!DSA_generate_parameters_ex(dsa, 1024,NULL,0,NULL,NULL,NULL))
        goto end;
    if (!DSA_generate_key(dsa))
        goto end;
    if (bad)
        BN_add_word(dsa->pub_key, 1);

    if (!FIPS_digestinit(&mctx, EVP_sha256()))
        goto end;
    if (!FIPS_digestupdate(&mctx, dgst, sizeof(dgst) - 1))
        goto end;
    sig = FIPS_dsa_sign_ctx(dsa, &mctx);
    if (!sig)
        goto end;

    if (!FIPS_digestinit(&mctx, EVP_sha256()))
        goto end;
    if (!FIPS_digestupdate(&mctx, dgst, sizeof(dgst) - 1))
        goto end;
    r = FIPS_dsa_verify_ctx(dsa, &mctx, sig);
end:
    if (sig)
        FIPS_dsa_sig_free(sig);
    FIPS_md_ctx_cleanup(&mctx);
    if (dsa)
        FIPS_dsa_free(dsa);
    if (r != 1)
        return 0;
    return 1;
}
예제 #20
0
파일: pdsa.c 프로젝트: pete/freenote-probe
/**
	load_probekeys
	Loads public and private keys for the probe.  If it cannot load them,
	it generates and saves them.  Returns 0 if we get actual keys and -1 if
	no keys could be loaded or generated.
*/
static int load_probekeys()
{
	int r;
	char *pubfn, *privfn;

	pubfn = fm_abs(FM_KEY_PROBE_PUBLIC);
	privfn = fm_abs(FM_KEY_PROBE_PRIVATE);
	r = load_keys(pubfn, privfn, &probe);

	if(r == -1 && DSA_generate_key(probe)) {
		save_keys(pubfn, privfn, probe);
		r = 0;
	}

	free(pubfn);
	free(privfn);

	return r;
}
예제 #21
0
static void keypair()
{
    char buf[1024];
    char lbuf[1024];
    char *keyword, *value;
    int nmod = 0;

    while (fgets(buf, sizeof buf, stdin) != NULL) {
        if (!parse_line(&keyword, &value, lbuf, buf)) {
            fputs(buf, stdout);
            continue;
        }
        if (!strcmp(keyword, "[mod"))
            nmod = atoi(value);
        else if (!strcmp(keyword, "N")) {
            DSA *dsa;
            int n = atoi(value);

            printf("[mod = %d]\n\n", nmod);
            dsa = FIPS_dsa_new();
            if (!DSA_generate_parameters_ex
                    (dsa, nmod, NULL, 0, NULL, NULL, NULL)) {
                do_print_errors();
                exit(1);
            }
            pbn("P", dsa->p);
            pbn("Q", dsa->q);
            pbn("G", dsa->g);
            putc('\n', stdout);

            while (n--) {
                if (!DSA_generate_key(dsa)) {
                    do_print_errors();
                    exit(1);
                }

                pbn("X", dsa->priv_key);
                pbn("Y", dsa->pub_key);
                putc('\n', stdout);
            }
        }
    }
}
예제 #22
0
/* DSA: generate key and sign a known digest, then verify the signature
 * against the digest
*/
static int FIPS_dsa_test()
    {
    DSA *dsa = NULL;
    unsigned char dgst[] = "etaonrishdlc";
    unsigned char sig[256];
    unsigned int siglen;

    ERR_clear_error();
    dsa = DSA_generate_parameters(512,NULL,0,NULL,NULL,NULL,NULL);
    if (!dsa)
	return 0;
    if (!DSA_generate_key(dsa))
	return 0;
    if ( DSA_sign(0,dgst,sizeof(dgst) - 1,sig,&siglen,dsa) != 1 )
	return 0;
    if ( DSA_verify(0,dgst,sizeof(dgst) - 1,sig,siglen,dsa) != 1 )
	return 0;
    DSA_free(dsa);
    return 1;
    }
void siggen()
    {
    char buf[1024];
    int nmod=0;
    DSA *dsa=NULL;

    while(fgets(buf,sizeof buf,stdin) != NULL)
	{
	if(!strncmp(buf,"[mod = ",7))
	    {
	    nmod=atoi(buf+7);
	    printf("[mod = %d]\n\n",nmod);

	    dsa=DSA_generate_parameters(nmod,NULL,0,NULL,NULL,NULL,NULL);
	    pbn("P",dsa->p);
	    pbn("Q",dsa->q);
	    pbn("G",dsa->g);
	    putc('\n',stdout);
	    }
	else if(!strncmp(buf,"Msg = ",6))
	    {
	    unsigned char msg[1024];
	    unsigned char hash[20];
	    int n;
	    DSA_SIG *sig;

	    n=hex2bin(buf+6,msg);
	    pv("Msg",msg,n);

	    DSA_generate_key(dsa);
	    pbn("Y",dsa->pub_key);

	    SHA1(msg,n,hash);
	    sig=DSA_do_sign(hash,sizeof hash,dsa);
	    pbn("R",sig->r);
	    pbn("S",sig->s);
	    putc('\n',stdout);
	    }
	}
    }
예제 #24
0
파일: pki.c 프로젝트: open-iscsi/open-isns
/*
 * DSA key generation
 */
EVP_PKEY *
isns_dsa_generate_key(void)
{
	EVP_PKEY *pkey;
	DSA	*dsa = NULL;

	if (!(dsa = isns_dsa_load_params(isns_config.ic_dsa.param_file)))
		goto failed;

	if (!DSA_generate_key(dsa)) {
		isns_dsasig_report_errors("Failed to generate DSA key",
				isns_error);
		goto failed;
	}

	pkey = EVP_PKEY_new();
	EVP_PKEY_assign_DSA(pkey, dsa);
	return pkey;

failed:
	if (dsa)
		DSA_free(dsa);
	return NULL;
}
예제 #25
0
파일: gendsa.c 프로젝트: LucidOne/Rovio
int MAIN(int argc, char **argv)
	{
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	DSA *dsa=NULL;
	int ret=1;
	char *outfile=NULL;
	char *inrand=NULL,*dsaparams=NULL;
	char *passargout = NULL, *passout = NULL;
	BIO *out=NULL,*in=NULL;
	const EVP_CIPHER *enc=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#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;

	argv++;
	argc--;
	for (;;)
		{
		if (argc <= 0) break;
		if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (strcmp(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#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 if (strcmp(*argv,"-") == 0)
			goto bad;
#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_SEED
		else if (strcmp(*argv,"-seed") == 0)
			enc=EVP_seed_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 (**argv != '-' && dsaparams == NULL)
			{
			dsaparams = *argv;
			}
		else
			goto bad;
		argv++;
		argc--;
		}

	if (dsaparams == NULL)
		{
bad:
		BIO_printf(bio_err,"usage: gendsa [args] dsaparam-file\n");
		BIO_printf(bio_err," -out file - output the key to 'file'\n");
#ifndef OPENSSL_NO_DES
		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");
#endif
#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
#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");
		BIO_printf(bio_err," dsaparam-file\n");
		BIO_printf(bio_err,"           - a DSA parameter file as generated by the dsaparam command\n");
		goto end;
		}

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

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


	in=BIO_new(BIO_s_file());
	if (!(BIO_read_filename(in,dsaparams)))
		{
		perror(dsaparams);
		goto end;
		}

	if ((dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL)) == NULL)
		{
		BIO_printf(bio_err,"unable to load DSA parameter file\n");
		goto end;
		}
	BIO_free(in);
	in = NULL;
		
	out=BIO_new(BIO_s_file());
	if (out == NULL) 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 DSA key, %d bits\n",
							BN_num_bits(dsa->p));
	if (!DSA_generate_key(dsa)) goto end;

	app_RAND_write_file(NULL, bio_err);

	if (!PEM_write_bio_DSAPrivateKey(out,dsa,enc,NULL,0,NULL, passout))
		goto end;
	ret=0;
end:
	if (ret != 0)
		ERR_print_errors(bio_err);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (dsa != NULL) DSA_free(dsa);
	if(passout) OPENSSL_free(passout);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
예제 #26
0
파일: testDSA.c 프로젝트: oplol/univ-code
int main()
{
	FILE *fp;
    int len, i;

    MD5_CTX ctx;
    unsigned char buf[1000];
    unsigned char md5sum[16];
                
    
    MD5_Init(&ctx);
    if(!( fp = fopen("input.dat", "rb")))
    {
        printf("\nFailed to open file\n"); return (1);
    }
    
    while((len = fread( buf, 1, sizeof(buf), fp ) ) > 0 )
    {
        MD5_Update(&ctx, buf, len);
    }
         
    MD5_Final(md5sum, &ctx);
    
	printf("MD5(input.dat) = ");
    for( i = 0; i < 16; i++ )
    {
       printf("%02x", md5sum[i]);
    }
    printf("\n");


   DSA *key;
   FILE *fp1, *fp2;
   /*unsigned char digest[8] = "1234567";*/
   int siglen;
   unsigned char signature[1000];
   int retcode;

   key = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, NULL, NULL);

   if (key == NULL)
   {
      printf("\nFailed to generate parameters\n");
      exit(1);
   }
   fp1 = fopen("params.dat", "w");
   DSAparams_print_fp(fp1, key);
   fclose(fp1);

   DSA_generate_key(key);
   if (key == NULL)
   {
      printf("\nFailed to generate key\n");
      exit(1);
   }

   fp2 = fopen("key.dat", "w");

   DSA_print_fp(fp2, key, 0);
   fclose(fp2);

   retcode = DSA_sign(0, md5sum, 8, signature, &siglen, key);
   if (retcode == 0)
   {
      printf("\n *** Error in signing ***\n\n");
      exit(1);
   }

   FILE *fp3;
   fp3 = fopen("signature.dat", "w");
   fputs(signature, fp3);
   fclose(fp3);

   printf("\nSignature of the hash = ");
   printf("%s\n",signature);

   retcode = DSA_verify(0, md5sum, 8, signature, siglen, key);
   if (retcode == 1)
      printf("\n *** Valid signature ***\n\n");
   if (retcode == 0)
      printf("\n *** Incorrect signature ***\n\n");
   if (retcode == -1)
      printf("\n *** Error in verifying ***\n\n");

   DSA_free(key);
   return 0;
}
예제 #27
0
파일: dsaparam.c 프로젝트: LucidOne/Rovio
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);
	}
예제 #28
0
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);
	}
예제 #29
0
파일: dsatest.c 프로젝트: Astel/openssl
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);
}
예제 #30
0
DVT_STATUS CERTIFICATE_CLASS::generateFiles(LOG_CLASS* logger_ptr,
											const char* signerCredentialsFile_ptr, 
											const char* credentialsPassword_ptr,
											const char* keyPassword_ptr,
											const char* keyFile_ptr, 
											const char* certificateFile_ptr)

//  DESCRIPTION     : Generate a certificate and key files from this class.
//  PRECONDITIONS   :
//  POSTCONDITIONS  :
//  EXCEPTIONS      : 
//  NOTES           : If signerCredentialsFile_ptr is NULL, a self signed 
//					: certificate will be generated.
//					:
//					: Returns:  MSG_OK, MSG_LIB_NOT_EXIST, MSG_FILE_NOT_EXIST, 
//					: MSG_ERROR, MSG_INVALID_PASSWORD 
//<<===========================================================================
{
	DVT_STATUS ret = MSG_ERROR;
	unsigned long err;
	OPENSSL_CLASS* openSsl_ptr;
	BIO* caBio_ptr = NULL;
	EVP_PKEY* caPrivateKey_ptr = NULL;
	X509* caCertificate_ptr = NULL;
	EVP_PKEY* key_ptr = NULL;
	X509* cert_ptr = NULL;
	X509_NAME* name_ptr;
	time_t effectiveTime;
	time_t expirationTime;
	EVP_PKEY* tmpKey_ptr;
	const EVP_MD *digest_ptr;
	BIO* pkBio_ptr = NULL;
	const EVP_CIPHER *cipher_ptr;
	BIO* certBio_ptr = NULL;

	// check for the existence of the OpenSSL DLLs
	openSsl_ptr = OPENSSL_CLASS::getInstance();
	if (openSsl_ptr == NULL)
	{
		return MSG_LIB_NOT_EXIST;
	}

	// clear the error queue
	ERR_clear_error();

	if (signerCredentialsFile_ptr != NULL)
	{
		// open the credentials file
		caBio_ptr = BIO_new(BIO_s_file_internal());
		if (caBio_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting up to read CA credentials file");
			goto end;
		}
		if (BIO_read_filename(caBio_ptr, signerCredentialsFile_ptr) <= 0)
		{
			err = ERR_peek_error();
			if ((ERR_GET_LIB(err) == ERR_LIB_SYS) && (ERR_GET_REASON(err) == ERROR_FILE_NOT_FOUND))
			{
				// file does not exist
				ERR_clear_error(); // eat any errors
				ret = MSG_FILE_NOT_EXIST;
			}
			else
			{
				openSsl_ptr->printError(logger_ptr, LOG_ERROR, "opening CA credentials file for reading");
			}
			goto end;
		}

		// read the certificate authority's private key
		caPrivateKey_ptr = PEM_read_bio_PrivateKey(caBio_ptr, NULL, NULL, (void*)credentialsPassword_ptr);
		if (caPrivateKey_ptr == NULL)
		{
			err = ERR_peek_error();
			if ((ERR_GET_LIB(err) == ERR_LIB_EVP) && (ERR_GET_REASON(err) == EVP_R_BAD_DECRYPT))
			{
				// bad password
				ERR_clear_error(); // eat any errors
				ret = MSG_INVALID_PASSWORD;
			}
			else
			{
				openSsl_ptr->printError(logger_ptr, LOG_ERROR, "reading private key from CA credentials file");
			}
			goto end;
		}

		// read the certificate authority's certificate
		caCertificate_ptr = PEM_read_bio_X509(caBio_ptr, NULL, NULL, (void*)credentialsPassword_ptr);
		if (caCertificate_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "reading CA certificate from CA credentials file");
			goto end;
		}
	}

	// generate the new private/public key pair
	if (signatureAlgorithmM.compare("RSA") == 0)
	{
		// RSA key
		RSA* rsa_key;

		rsa_key = RSA_generate_key(signatureKeyLengthM, RSA_3, NULL, 0);
		if (rsa_key == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "generating RSA key");
			goto end;
		}

		key_ptr = EVP_PKEY_new();
		if (key_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "creating RSA key");
			RSA_free(rsa_key);
			goto end;
		}

		EVP_PKEY_assign_RSA(key_ptr, rsa_key);
	}
	else
	{
		// DSA key
		DSA* dsa_key;

		dsa_key = DSA_generate_parameters(signatureKeyLengthM, NULL, 0, NULL, NULL, NULL, 0);
		if (dsa_key == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "generating DSA parameters");
			goto end;
		}

		if (DSA_generate_key(dsa_key) == 0)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "generating DSA key");
			DSA_free(dsa_key);
			goto end;
		}

		key_ptr = EVP_PKEY_new();
		if (key_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "creating DSA key");
			DSA_free(dsa_key);
			goto end;
		}

		EVP_PKEY_assign_DSA(key_ptr, dsa_key);
	}

	// create the certificate
	cert_ptr = X509_new();
	if (cert_ptr == NULL)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "creating certificate object");
		goto end;
	}

	// version
	if (X509_set_version(cert_ptr, (versionM - 1)) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting certificate version");
		goto end;
	}

	// subject
	name_ptr = openSsl_ptr->onelineName2Name(subjectM.c_str());
	if (name_ptr == NULL)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "parsing owner name");
		goto end;
	}

	if (X509_set_subject_name(cert_ptr, name_ptr) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting owner name in certificate");
		goto end;
	}

	// issuer
	if (signerCredentialsFile_ptr != NULL)
	{
		// CA signed
		name_ptr = X509_get_subject_name(caCertificate_ptr);
		if (name_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "getting name from CA certificate");
			goto end;
		}

		if (X509_set_issuer_name(cert_ptr, name_ptr) != 1)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting issuer name in certificate");
			goto end;
		}
	}
	else
	{
		// self signed
		name_ptr = X509_NAME_dup(name_ptr); // duplicate the name so it can be used again
		if (name_ptr == NULL)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "duplicating owner name");
			goto end;
		}

		if (X509_set_issuer_name(cert_ptr, name_ptr) != 1)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting issuer name in certificate");
			goto end;
		}
	}
	
	// public key
	if (X509_set_pubkey(cert_ptr, key_ptr) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting public key in certificate");
		goto end;
	}

	// valid dates
	effectiveTime = mktime(&effectiveDateM);
	expirationTime = mktime(&expirationDateM);
	if ((X509_time_adj(X509_get_notBefore(cert_ptr), 0, &effectiveTime) == NULL) ||
		(X509_time_adj(X509_get_notAfter(cert_ptr), 0, &expirationTime) == NULL))
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting valid dates in certificate");
		goto end;
	}

	// serial number, use the current time_t
	ASN1_INTEGER_set(X509_get_serialNumber(cert_ptr), (unsigned)time(NULL));

	// sign the certificate
	if (signerCredentialsFile_ptr != NULL)
	{
		// CA signed
		tmpKey_ptr = caPrivateKey_ptr;
	}
	else
	{
		// self signed
		tmpKey_ptr = key_ptr;
	}

	if (EVP_PKEY_type(tmpKey_ptr->type) == EVP_PKEY_RSA)
	{
		digest_ptr = EVP_sha1();
	}
	else if (EVP_PKEY_type(tmpKey_ptr->type) == EVP_PKEY_DSA)
	{
		digest_ptr = EVP_dss1();
	}
	else
	{
		if (logger_ptr)
		{
			logger_ptr->text(LOG_ERROR, 1, "Unsupported key type in CA private key");
		}
		goto end;
	}

	if (!X509_sign(cert_ptr, tmpKey_ptr, digest_ptr))
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "signing certificate");
		goto end;
	}

	// write out the private key
	// open the private key file
	pkBio_ptr = BIO_new(BIO_s_file_internal());
	if (pkBio_ptr == NULL)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting up to write private key file");
		goto end;
	}
	if (BIO_write_filename(pkBio_ptr, (void *)keyFile_ptr) <= 0)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "opening to write private key file");
		goto end;
	}

	if ((keyPassword_ptr != NULL) && (strlen(keyPassword_ptr) > 0))
	{
		// we have a password, use 3DES to encrypt the key
		cipher_ptr = EVP_des_ede3_cbc();
	}
	else
	{
		// there is no password, don't encrypt the key
		cipher_ptr = NULL;
	}

	// write out the private key
	if (PEM_write_bio_PKCS8PrivateKey(pkBio_ptr, key_ptr, cipher_ptr, 
										NULL, 0, NULL, (void *)keyPassword_ptr) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "writing private key");
		goto end;
	}

	// write the certificate file
	// open the certificate file
	certBio_ptr = BIO_new(BIO_s_file_internal());
	if (certBio_ptr == NULL)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "setting up to write certificate file");
		goto end;
	}
	if (BIO_write_filename(certBio_ptr, (void *)certificateFile_ptr) <= 0)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "opening to write certificate file");
		goto end;
	}

	// write the new certificate
	if (PEM_write_bio_X509(certBio_ptr, cert_ptr) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "writing certificate");
		goto end;
	}

	// write the new certificate into the credential file 
	if (PEM_write_bio_X509(pkBio_ptr, cert_ptr) != 1)
	{
		openSsl_ptr->printError(logger_ptr, LOG_ERROR, "writing certificate");
		goto end;
	}


	if (signerCredentialsFile_ptr != NULL)
	{
		// write the CA certificate
		if (PEM_write_bio_X509(certBio_ptr, caCertificate_ptr) != 1)
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "writing CA certificate");
			goto end;
		}

		// loop reading certificates from the CA credentials file and writing them to the certificate file
		X509_free(caCertificate_ptr);
		while ((caCertificate_ptr = PEM_read_bio_X509(caBio_ptr, NULL, NULL, (void*)credentialsPassword_ptr)) != NULL)
		{
			// write the certificate
			if (PEM_write_bio_X509(certBio_ptr, caCertificate_ptr) != 1)
			{
				openSsl_ptr->printError(logger_ptr, LOG_ERROR, "writing certificate chain");
				goto end;
			}

			X509_free(caCertificate_ptr);
		}
		// check the error
		err = ERR_peek_error();
		if ((ERR_GET_LIB(err) == ERR_LIB_PEM) && (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
		{
			// end of data - this is normal
			ERR_clear_error();
		}
		else
		{
			openSsl_ptr->printError(logger_ptr, LOG_ERROR, "reading certificates from CA credentials file");
			goto end;
		}
	}


	ret = MSG_OK;

end:
	if (certBio_ptr != NULL) BIO_free(certBio_ptr);
	if (pkBio_ptr != NULL) BIO_free(pkBio_ptr);
	if (cert_ptr != NULL) X509_free(cert_ptr);
	if (key_ptr != NULL) EVP_PKEY_free(key_ptr);
	if (caCertificate_ptr != NULL) X509_free(caCertificate_ptr);
	if (caPrivateKey_ptr != NULL) EVP_PKEY_free(caPrivateKey_ptr);
	if (caBio_ptr != NULL) BIO_free(caBio_ptr);

	return ret;
}