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);
}
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);
		}
	    }
	}
    }
Exemple #3
0
main ()
{
    int i;

    BIGNUM *n;

    BN_CTX *ctx;

    unsigned char seed_buf[20];

    DSA *dsa;

    int counter, h;

    BIO *bio_err = NULL;

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

    memcpy (seed_buf, seed, 20);
    dsa = DSA_generate_parameters (1024, seed, 20, &counter, &h, cb, bio_err);

    if (dsa == NULL)
        DSA_print (bio_err, dsa, 0);
}
Exemple #4
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;
}
Exemple #5
0
/** dsa_init - this is called at startup.  Errors will return -1, and
 *  should be caught by the try() macro
 */
int dsa_init()
{
	char *fn; 

	ou_seed();	/* initialize the random seed, cannot fail */

	dispatch = NULL;

	probe = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, NULL, 
		NULL);
	if(probe == NULL) 
		return -1;

	try(load_probekeys());

	dispatch = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, 
		NULL, NULL);
	if(dispatch == NULL)
		return 0;	/* no big deal, yet */

	fn = fm_abs(FM_KEY_DISPATCH_PUBLIC);

	if(load_keys(fn, NULL, &dispatch) == -1) {
		DSA_free(dispatch);
		dispatch = NULL;
	}

	free(fn);
	
	return 0;
}

/** dsa_close -  frees up memory used for key signing and verification, run
 * this at exit */
void dsa_close()
{
	DSA_free(probe);
	DSA_free(dispatch);
}
Exemple #6
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;
}
/*
 * Generate DSA algorithm parameters from optional seed input, returning result
 * into NSS_DSAAlgParamss.[pqg]. This is called from both GenerateParameters and from
 * KeyPairGenerate (if no GenerateParameters has yet been called). 
 */
void DSAKeyPairGenContext::dsaGenParams(
	uint32				keySizeInBits,
	const void			*inSeed,		// optional
	unsigned			inSeedLen,
	NSS_DSAAlgParams 	&algParams,
	SecNssCoder			&coder)			// contents of algParams mallocd from here
{
	unsigned char seedBuf[SHA1_DIGEST_SIZE];
	void *seedPtr;
	
	/* validate key size */
	if((keySizeInBits < DSA_MIN_KEY_SIZE) || 
	   (keySizeInBits > DSA_MAX_KEY_SIZE) ||
	   (keySizeInBits & DSA_KEY_BITS_MASK)) {
		CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH);
	}
	
	/* seed from one of three sources */
	if(inSeed == NULL) {
		/* 20 random seed bytes */
		session().getRandomBytes(SHA1_DIGEST_SIZE, seedBuf);
		seedPtr = seedBuf;
	}
	else if(inSeedLen == SHA1_DIGEST_SIZE) {
		/* perfect */
		seedPtr = (void *)inSeed;
	}
	else {
		/* hash caller's seed */
		cspGenSha1Hash(inSeed, inSeedLen, seedBuf);
		seedPtr = seedBuf;
	}

	DSA *dsaKey = DSA_generate_parameters(keySizeInBits,
		(unsigned char *)seedPtr,	
		SHA1_DIGEST_SIZE,
		NULL,		// counter_ret
		NULL,		// h_ret
		NULL, 
		NULL);
	if(dsaKey == NULL) {
		throwRsaDsa("DSA_generate_parameters");
	}
	
	/* stuff dsaKey->[pqg] into a caller's NSS_DSAAlgParams */
	bnToCssmData(dsaKey->p, algParams.p, coder);
	bnToCssmData(dsaKey->q, algParams.q, coder);
	bnToCssmData(dsaKey->g, algParams.g, coder);
	
	DSA_free(dsaKey);
}
Exemple #8
0
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;
}
Exemple #9
0
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();
}
Exemple #10
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);
}
Exemple #11
0
main()
	{
	int i;
	BIGNUM *n;
	BN_CTX *ctx;
	unsigned char seed_buf[20];
	DSA *dsa;
	int counter,h;
	BIO *bio_err=NULL;

	if (bio_err == NULL)
		bio_err=BIO_new_fp(OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE);

	TINYCLR_SSL_MEMCPY(seed_buf,seed,20);
	dsa=DSA_generate_parameters(1024,seed,20,&counter,&h,cb,bio_err);

	if (dsa == NULL)
		DSA_print(bio_err,dsa,0);
	}
Exemple #12
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);
	    }
	}
    }
Exemple #14
0
bool OSSLDSA::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/)
{
	if ((ppParams == NULL) || (parameters == NULL))
	{
		return false;
	}

	size_t bitLen = (size_t) parameters;

	if (bitLen < getMinKeySize() || bitLen > getMaxKeySize())
	{
		ERROR_MSG("This DSA key size is not supported");

		return false;
	}

	DSA* dsa = DSA_generate_parameters(bitLen, NULL, 0, NULL, NULL, NULL, NULL);

	if (dsa == NULL)
	{
		ERROR_MSG("Failed to generate %d bit DSA parameters", bitLen);

		return false;
	}

	// Store the DSA parameters
	DSAParameters* params = new DSAParameters();

	ByteString p = OSSL::bn2ByteString(dsa->p); params->setP(p);
	ByteString q = OSSL::bn2ByteString(dsa->q); params->setQ(q);
	ByteString g = OSSL::bn2ByteString(dsa->g); params->setG(g);

	*ppParams = params;

	DSA_free(dsa);

	return true;
}
void pqg()
    {
    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))
	    {
	    int n=atoi(buf+4);

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

	    while(n--)
		{
		unsigned char seed[20];
		DSA *dsa;
		int counter;
		unsigned long h;

		dsa=DSA_generate_parameters(nmod,seed,0,&counter,&h,NULL,NULL);
		printf("P = %s\n",BN_bn2hex(dsa->p));
		printf("Q = %s\n",BN_bn2hex(dsa->q));
		printf("G = %s\n",BN_bn2hex(dsa->g));
		pv("Seed",seed,20);
		printf("c = %d\n",counter);
		printf("H = %lx\n",h);
		putc('\n',stdout);
		}
	    }
	else
	    fputs(buf,stdout);
	}
    }
Exemple #16
0
/**
	save_dispatch_key
	Saves a base64 encoded key, as well as keeping it for future use.  Pass
	it a key in the form of a null-terminated string.
	Returns -1 for error, 0 for success.
*/
int save_dispatch_key(const char *key)
{
	int r;
	char *pub;

	if(dispatch != NULL)
		return 0;	/* We have ignored you! */

	dispatch = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, 
		NULL, NULL);
	if(dispatch == NULL) {
		io_debug("%s:%s():%d  ", __FILE__, __func__, __LINE__);
		io_err("Not enough free memory!  The walls are closing in!\n");
		return -1;
	}

	pub = fm_abs(FM_KEY_DISPATCH_PUBLIC);

	r = !fm_write(FM_KEY_DISPATCH_PUBLIC, key, strlen(key));
	r |= load_keys(pub, NULL, &dispatch);
	free(pub);

	return r;
}
Exemple #17
0
void
keynote_keygen(int argc, char *argv[])
{
    int begin = KEY_PRINT_OFFSET, prlen = KEY_PRINT_LENGTH;
    char *foo, *privalgname, seed[SEED_LEN];
    int alg, enc, ienc, len = 0, counter;
    struct keynote_deckey dc;
    unsigned long h;
    DSA *dsa;
    RSA *rsa;
    FILE *fp;
    char *algname;

    if ((argc != 5) && (argc != 6) && (argc != 7))
    {
	keygenusage();
	exit(0);
    }

    /* Fix algorithm name */
    if (argv[1][strlen(argv[1]) - 1] != ':')
    {
	int len = strlen(argv[1]) + 2;

        fprintf(stderr, "Algorithm name [%s] should be terminated with a "
		"colon, fixing.\n", argv[1]);
	algname = (char *) calloc(len, sizeof(char));
	if (algname == (char *) NULL)
	{
	    perror("calloc()");
	    exit(1);
	}

	strlcpy(algname, argv[1], len);
	algname[strlen(algname)] = ':';
    }
    else
	algname = argv[1];

    if (argc > 5)
    {
	begin = atoi(argv[5]);
	if (begin <= -1)
	{
	    fprintf(stderr, "Erroneous value for print-offset parameter.\n");
	    exit(1);
	}
    }

    if (argc > 6)
    {
	prlen = atoi(argv[6]);
	if (prlen <= 0)
	{
	    fprintf(stderr, "Erroneous value for print-length parameter.\n");
	    exit(1);
	}
    }

    if (strlen(algname) + 2 > prlen)
    {
	fprintf(stderr, "Parameter ``print-length'' should be larger "
		"than the length of AlgorithmName (%lu)\n",
		(unsigned long) strlen(algname));
	exit(1);
    }

    alg = keynote_get_key_algorithm(algname, &enc, &ienc);
    len = atoi(argv[2]);

    if (len <= 0)
    {
	fprintf(stderr, "Invalid specified keysize %d\n", len);
	exit(1);
    }

    if ((alg == KEYNOTE_ALGORITHM_DSA) &&
	(ienc == INTERNAL_ENC_ASN1) &&
	((enc == ENCODING_HEX) || (enc == ENCODING_BASE64)))
    {
        RAND_bytes(seed, SEED_LEN);

	dsa = DSA_generate_parameters(len, seed, SEED_LEN, &counter, &h, NULL
				      , NULL);

	if (dsa == (DSA *) NULL)
	{
	    ERR_print_errors_fp(stderr);
	    exit(1);
	}

	if (DSA_generate_key(dsa) != 1)
	{
	    ERR_print_errors_fp(stderr);
	    exit(1);
	}

	dc.dec_algorithm = KEYNOTE_ALGORITHM_DSA;
	dc.dec_key = (void *) dsa;

	foo = kn_encode_key(&dc, ienc, enc, KEYNOTE_PUBLIC_KEY);
	if (foo == (char *) NULL)
	{
	    fprintf(stderr, "Error encoding key (errno %d)\n", keynote_errno);
	    exit(1);
	}

	if (!strcmp(argv[3], "-"))
	  fp = stdout;
	else
	{
	    fp = fopen(argv[3], "w");
	    if (fp == (FILE *) NULL)
	    {
		perror(argv[3]);
		exit(1);
	    }
	}

	print_key(fp, algname, foo, begin, prlen);
	free(foo);

	if (strcmp(argv[3], "-"))
	  fclose(fp);

	foo = kn_encode_key(&dc, ienc, enc, KEYNOTE_PRIVATE_KEY);
	if (foo == (char *) NULL)
	{
	    fprintf(stderr, "Error encoding key (errno %d)\n", keynote_errno);
	    exit(1);
	}

	if (!strcmp(argv[4], "-"))
	{
	    fp = stdout;
	    if (!strcmp(argv[3], "-"))
	      printf("===========================\n");
	}
	else
	{
	    fp = fopen(argv[4], "w");
	    if (fp == (FILE *) NULL)
	    {
		perror(argv[4]);
		exit(1);
	    }
	}

	len = strlen(KEYNOTE_PRIVATE_KEY_PREFIX) + strlen(foo) + 1;
	privalgname = (char *) calloc(len, sizeof(char));
	if (privalgname == (char *) NULL)
	{
	    perror("calloc()");
	    exit(1);
	}
	snprintf(privalgname, len, "%s%s", KEYNOTE_PRIVATE_KEY_PREFIX, algname);
	print_key(fp, privalgname, foo, begin, prlen);
	free(privalgname);
	free(foo);

	if (strcmp(argv[4], "-"))
	  fclose(fp);

	exit(0);
    }

    if ((alg == KEYNOTE_ALGORITHM_RSA) &&
	(ienc == INTERNAL_ENC_PKCS1) &&
	((enc == ENCODING_HEX) || (enc == ENCODING_BASE64)))
    {
	rsa = RSA_generate_key(len, DEFAULT_PUBLIC, NULL, NULL);

	if (rsa == (RSA *) NULL)
	{
	    ERR_print_errors_fp(stderr);
	    exit(1);
	}

	dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
	dc.dec_key = (void *) rsa;

	foo = kn_encode_key(&dc, ienc, enc, KEYNOTE_PUBLIC_KEY);
	if (foo == (char *) NULL)
	{
	    fprintf(stderr, "Error encoding key (errno %d)\n", keynote_errno);
	    exit(1);
	}

	if (!strcmp(argv[3], "-"))
	  fp = stdout;
	else
	{
	    fp = fopen(argv[3], "w");
	    if (fp == (FILE *) NULL)
	    {
		perror(argv[3]);
		exit(1);
	    }
	}

	print_key(fp, algname, foo, begin, prlen);
	free(foo);

	if (strcmp(argv[3], "-"))
	  fclose(fp);

	foo = kn_encode_key(&dc, ienc, enc, KEYNOTE_PRIVATE_KEY);
	if (foo == (char *) NULL)
	{
	    fprintf(stderr, "Error encoding key (errno %d)\n", keynote_errno);
	    exit(1);
	}

	if (!strcmp(argv[4], "-"))
	{
	    fp = stdout;
	    if (!strcmp(argv[3], "-"))
	      printf("===========================\n");
	}
	else
	{
	    fp = fopen(argv[4], "w");
	    if (fp == (FILE *) NULL)
	    {
		perror(argv[4]);
		exit(1);
	    }
	}

	len = strlen(KEYNOTE_PRIVATE_KEY_PREFIX) + strlen(foo) + 1;
	privalgname = (char *) calloc(len, sizeof(char));
	if (privalgname == (char *) NULL)
	{
	    perror("calloc()");
	    exit(1);
	}
	snprintf(privalgname, len, "%s%s", KEYNOTE_PRIVATE_KEY_PREFIX, algname);
	print_key(fp, privalgname, foo, begin, prlen);
	free(privalgname);
	free(foo);

	if (strcmp(argv[4], "-"))
	  fclose(fp);

	exit(0);
    }

    /* More algorithms here */

    fprintf(stderr, "Unknown/unsupported algorithm [%s]\n", algname);
    exit(1);
}
Exemple #18
0
int main(int argc, char **argv)
	{
	DSA *dsa=NULL;
	int counter,ret=0,i,j;
	unsigned char buf[256];
	unsigned long h;
	unsigned char sig[256];
	unsigned int siglen;

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

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

	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

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

	dsa=DSA_generate_parameters(512,seed,20,&counter,&h,dsa_cb,bio_err);

	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=%d\n",counter,h);
		
	if (dsa == NULL) goto end;
	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;
		}

	i=BN_bn2bin(dsa->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(dsa->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(dsa->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_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);
	ERR_remove_state(0);
	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err = NULL;
		}
	exit(!ret);
	return(0);
	}
Exemple #19
0
void xr_dsa::generate_params()
{
	int counter;
	unsigned long	long_ret;
	string256		random_string;
	xr_sprintf					(random_string, "%I64d_%s", CPU::QPC(), rnd_seed);
	//sprintf_s					(random_string, "%s", rnd_seed);
	unsigned char*	rnd_seed	= static_cast<unsigned char*>((void*)random_string);
	unsigned int	rnd_ssize	= xr_strlen(random_string);
	DSA* tmp_dsa_params	= DSA_generate_parameters(
		key_bit_length,
		rnd_seed,
		rnd_ssize,
		&counter,
		&long_ret,
		dsa_genparams_cb,
		NULL
	);
	DSA_generate_key	(tmp_dsa_params);

	VERIFY				(tmp_dsa_params->p->top * sizeof(u32)		== public_key_length);
	VERIFY				(tmp_dsa_params->q->top * sizeof(u32)		== private_key_length);
	VERIFY				(tmp_dsa_params->g->top * sizeof(u32)		== public_key_length);
	VERIFY				(tmp_dsa_params->pub_key->top * sizeof(u32) == public_key_length);
	VERIFY				(tmp_dsa_params->priv_key->top * sizeof(u32)== private_key_length);
	
	Msg("// DSA params ");
	
	Msg("u8 const p_number[crypto::xr_dsa::public_key_length] = {");
	print_big_number	(tmp_dsa_params->p);
	Msg("};//p_number");

	
	Msg("u8 const q_number[crypto::xr_dsa::private_key_length] = {");
	print_big_number	(tmp_dsa_params->q);
	Msg("};//q_number");
	
	
	Msg("u8 const g_number[crypto::xr_dsa::public_key_length] = {");
	print_big_number	(tmp_dsa_params->g);
	Msg("};//g_number");

	Msg("u8 const public_key[crypto::xr_dsa::public_key_length] = {");
	print_big_number	(tmp_dsa_params->pub_key);
	Msg("};//public_key");

	
	u8	priv_bin[private_key_length];
	BN_bn2bin			(tmp_dsa_params->priv_key, priv_bin);
	Msg("// Private key:");
	for (int i = 0; i < private_key_length; ++i)
	{
		Msg("	m_private_key.m_value[%d]	= 0x%02x;", i, priv_bin[i]);
	}

	u8	debug_digest[]		= "this is a test";
	u8	debug_bad_digest[]	= "this as a test";

	u32		siglen			= DSA_size(tmp_dsa_params);
	u8*		sig				= static_cast<u8*>(_alloca(siglen));

	BIGNUM	bn_sign;
	BN_init					(&bn_sign);
	
	VERIFY	(DSA_sign(0, debug_digest, sizeof(debug_digest), sig, &siglen, tmp_dsa_params) == 1);

	BN_bin2bn				(sig, siglen, &bn_sign);
	shared_str sig_str		= BN_bn2hex(&bn_sign);
	
	BIGNUM*	bn_rsing		= NULL;
	ZeroMemory				(sig, siglen);
	BN_hex2bn				(&bn_rsing, sig_str.c_str());
	BN_bn2bin				(bn_rsing, sig);
	BN_free					(bn_rsing);

	VERIFY	(DSA_verify(0, debug_digest, sizeof(debug_digest), sig, siglen, tmp_dsa_params) == 1);

	VERIFY	(DSA_verify(0, debug_bad_digest, sizeof(debug_bad_digest), sig, siglen, tmp_dsa_params) == 0);

	DSA_free(tmp_dsa_params);
}
Exemple #20
0
int main() {
    DSA *priv;
    lootr_otr_ctx_t *otr;
    lootr_otr_cbs_t cbs;
    unsigned char seed[20] = {};
    uint8_t *msg = NULL;
    uint8_t *reply_buf = NULL;
    uint32_t reply_len, len;
    int suppress;

    priv = DSA_generate_parameters(1024, seed, sizeof(seed), NULL, NULL, NULL,
            NULL);
    assert(priv);
    assert(DSA_generate_key(priv));

    cbs.on_warn = error;
    cbs.on_error = error;
    assert(!lootr_otr_ctx_new(&otr, &cbs, priv));

    while ((len = getdelim((char **)&msg, (size_t *)&len, '.', stdin)) >= 0) {
        int ret;
        uint8_t *p1, *p2;
        uint32_t new_len = len;
        lootr_msg_state_t state;
        assert(!lootr_otr_state(otr, &state));
        if (state == MSG_STATE_PLAINTEXT || (len > 0 && msg[0] == '?')) {
            p1 = p2 = msg;
            while (p2 != msg + len) {
                if (*p2 == '\n' || *p2 == ' ') {
                    --new_len;
                }
                else {
                    *p1 = *p2;
                    ++p1;
                }
                ++p2;
            }
            len = new_len;
            
            ret = lootr_otr_handle_msg(otr, msg, &len, &reply_buf, 
                        &reply_len, &suppress);
            assert(!ret);
            assert(len <= new_len);
            printf("State: %d\n", otr->ake->state);
            printf("Received%s: ", suppress ? " (suppressed)" : "");
            fwrite(msg, len, 1, stdout);
            printf("\n");
            if (reply_buf) {
                printf("Replying: ");
                fwrite(reply_buf, reply_len, 1, stdout);
                printf("\n");
                free(reply_buf);
                reply_buf = NULL;
            }
        }
        else {
            ret = lootr_otr_transform_msg(otr, msg, len, &reply_buf, 
                    &reply_len);
            assert(!ret);
            assert(reply_buf);
            printf("Sending: ");
            fwrite(reply_buf, reply_len, 1, stdout);
            printf("\n");
            free(reply_buf);
            reply_buf = NULL;
        }
        free(msg);
        msg = NULL;
    }

    while ((len = getdelim((char **)&msg, (size_t *)&len, '.', stdin)) >= 0) {
        if (msg[0] != '?') {
        }
    }

    lootr_otr_ctx_free(otr);
    DSA_free(priv);
    return 0;
}
Exemple #21
0
int genrequest(char department[], char cname0[]) {

   X509_REQ 	*webrequest 	 = NULL;
   EVP_PKEY	*pubkey		 = NULL;
   X509_NAME 	*reqname	 = NULL;
   DSA 		*mydsa		 = NULL;
   RSA 		*myrsa		 = NULL;
   BIO 		*outbio		 = NULL;
   X509_NAME_ENTRY      *e;
   int                  i;
   FILE                         *fp, *fp2;

   char         buf[80]		 = "";
   char         country[81]      = "UK";
   char         province[81]     = "Gloucestershire";
   char         locality[81]     = "Tetbury";
   char         organisation[81] = "TETBURY SOFTWARE SERVICES Ltd";
   char 	email_addr[81]   = "*****@*****.**";
   char 	cname1[81]       = "";
   char 	cname2[81]       = "";
   char 	surname[81]      = "";
   char 	givenname[81]    = "";

   char 	keytype[81]      = "rsa";
   int	 	rsastrength	 = 4096;
   int	 	dsastrength	 = 0;


/* we do not accept requests with no data, i.e. being empty with just a 
   public key. Although technically possible to sign and create a cert,
   they don't make much sense. We require here at least one CN supplied.    */

   if(strlen(cname0) == 0 && strlen(cname1) == 0 && strlen(cname2) == 0)
     printf("Error supply at least one CNAME in request subject");

/* -------------------------------------------------------------------------- *
 * These function calls are essential to make many PEM + other openssl        *
 * functions work. It is not well documented, I found out after looking into  *
 * the openssl source directly.                                               *
 * needed by: PEM_read_PrivateKey(), X509_REQ_verify() ...                    *
 * -------------------------------------------------------------------------- */
   OpenSSL_add_all_algorithms();
   ERR_load_crypto_strings();

/* ------------------------------------------------------------------------- *
 * Generate the key pair based on the selected keytype                       *
 * ------------------------------------------------------------------------- */

   if ((pubkey=EVP_PKEY_new()) == NULL)
      printf("Error creating EVP_PKEY structure.");

   if(strcmp(keytype, "rsa") == 0) {

      myrsa = RSA_new();
      if (! (myrsa = RSA_generate_key(rsastrength, RSA_F4, NULL, NULL)))
         printf("Error generating the RSA key.");

      if (!EVP_PKEY_assign_RSA(pubkey,myrsa))
         printf("Error assigning RSA key to EVP_PKEY structure.");
   }
   else if(strcmp(keytype, "dsa") == 0) {

      mydsa = DSA_new();
      mydsa = DSA_generate_parameters(dsastrength, NULL, 0, NULL, NULL,
                                                                  NULL, NULL);
      if (! (DSA_generate_key(mydsa)))
         printf("Error generating the DSA key.");

      if (!EVP_PKEY_assign_DSA(pubkey,mydsa))
         printf("Error assigning DSA key to EVP_PKEY structure.");
   }
   else
      printf("Error: Wrong keytype - choose either RSA or DSA.");

/* ------------------------------------------------------------------------- *
 * Generate the certificate request from scratch                             *
 * ------------------------------------------------------------------------- */

   if ((webrequest=X509_REQ_new()) == NULL)
      printf("Error creating new X509_REQ structure.");

   if (X509_REQ_set_pubkey(webrequest, pubkey) == 0)
      printf("Error setting public key for X509_REQ structure.");

   if ((reqname=X509_REQ_get_subject_name(webrequest)) == NULL)
      printf("Error setting public key for X509_REQ structure.");

   /* The following functions create and add the entries, working out  *
    * the correct string type and performing checks on its length.     *
    * We also check the return value for errors...                     */

   if(strlen(country) != 0)
      X509_NAME_add_entry_by_txt(reqname,"C", MBSTRING_ASC, 
                           (unsigned char*) country, -1, -1, 0);
   if(strlen(province) != 0)
      X509_NAME_add_entry_by_txt(reqname,"ST", MBSTRING_ASC,
                           (unsigned char *) province, -1, -1, 0);
   if(strlen(locality) != 0)
      X509_NAME_add_entry_by_txt(reqname,"L", MBSTRING_ASC,
                          (unsigned char *) locality, -1, -1, 0);
   if(strlen(organisation) != 0)
      X509_NAME_add_entry_by_txt(reqname,"O", MBSTRING_ASC,
                      (unsigned char *) organisation, -1, -1, 0);
   if(strlen(department) != 0)
      X509_NAME_add_entry_by_txt(reqname,"OU", MBSTRING_ASC,
                         (unsigned char *) department, -1, -1, 0);
   if(strlen(email_addr) != 0)
      X509_NAME_add_entry_by_txt(reqname,"emailAddress", MBSTRING_ASC,
			(unsigned char *)  email_addr, -1, -1, 0);
   if(strlen(cname0) != 0)
      X509_NAME_add_entry_by_txt(reqname,"CN", MBSTRING_ASC,
                                   (unsigned char *) cname0, -1, -1, 0);
   if(strlen(cname1) != 0)
      X509_NAME_add_entry_by_txt(reqname,"CN", MBSTRING_ASC,
                                   (unsigned char *) cname1, -1, -1, 0);
   if(strlen(cname2) != 0)
      X509_NAME_add_entry_by_txt(reqname,"CN", MBSTRING_ASC,
                                   (unsigned char *) cname2, -1, -1, 0);
   if(strlen(surname) != 0)
      X509_NAME_add_entry_by_txt(reqname,"SN", MBSTRING_ASC,
                                   (unsigned char *) surname, -1, -1, 0);
   if(strlen(givenname) != 0)
      X509_NAME_add_entry_by_txt(reqname,"GN", MBSTRING_ASC,
                                 (unsigned char *) givenname, -1, -1, 0);

/* ------------------------------------------------------------------------- *
 * Sign the certificate request: md5 for RSA keys, dss for DSA keys          *
 * ------------------------------------------------------------------------- */

   if(strcmp(keytype, "rsa") == 0) {
      if (!X509_REQ_sign(webrequest,pubkey,EVP_md5()))
         printf("Error MD5 signing X509_REQ structure.");
   }
   else if(strcmp(keytype, "dsa") == 0) {
      if (!X509_REQ_sign(webrequest,pubkey,EVP_dss()))
         printf("Error DSS signing X509_REQ structure.");
   }

/* ------------------------------------------------------------------------- *
 *  and sort out the content plus start the html output                      *
 * ------------------------------------------------------------------------- */

   if (! (fp=fopen("clave_publica.pem", "w")))
        printf("No puedo crear el fichero de la request");

   if (! (fp2=fopen("clave_privada.pem", "w")))
        printf("No puedo crear el fichero de la clave privada");

   outbio = BIO_new(BIO_s_file());
   BIO_set_fp(outbio, fp, BIO_NOCLOSE);

   if (! PEM_write_bio_X509_REQ(outbio, webrequest))
      printf("Error printing the request");

   for (i = 0; i < X509_NAME_entry_count(reqname); i++) {
      e = X509_NAME_get_entry(reqname, i);
      OBJ_obj2txt(buf, 80, e->object, 0);
   }

   PEM_write_PrivateKey(fp2,pubkey,NULL,NULL,0,0,NULL);


   BIO_free(outbio);
   fclose(fp);
   fclose(fp2);
   return(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

	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
		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
		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)
		{
		assert(need_rand);
		BIO_printf(bio_err,"Generating DSA parameters, %d bit long prime\n",num);
	        BIO_printf(bio_err,"This could take some time\n");
	        dsa=DSA_generate_parameters(num,NULL,0,NULL,NULL, dsa_cb,bio_err);
		}
	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);
	}
Exemple #23
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;
}
Exemple #24
0
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;
}
int CDSAKeyGenerator::Generate()
//Generate a DSA key with pre-determined length
	{
	unsigned char* pbSeed       = NULL; 
	DSA*		   pDSAParams   = NULL;
	FILE*		   fp		    = NULL;
	LPSTR		   pbPassword   = NULL;
	const _TCHAR*  pPrivKeyFile = NULL;
	
	int retVal  = FAIL;
	int retFunc = FAIL;

	pPrivKeyFile = GetPrivateKeyFile();
	if(!pPrivKeyFile)
		{
		PrintErrorInfo("Bad parameter error!", EGeneric, constparams);
		return 0;
		}
	
	OPENSSL_add_all_algorithms_conf();
	ERR_load_crypto_strings();

	int dwKeyLength = 0;
	dwKeyLength = GetKeyLength();
	
	try
		{
		retVal = GenerateSeed(dwKeyLength, &pbSeed);
		if(retVal != SUCCESS)
			{
			throw EMSCrypto;
			}

		//Generate DSA params (p,q and g)
		_tprintf(_T("\nGenerating DSA key ."));
		pDSAParams = DSA_generate_parameters(dwKeyLength, pbSeed, dwKeyLength, NULL, NULL, DSAKeyStatus, NULL);
		if(!pDSAParams)
			{
			PrintErrorInfo("Error generating DSA key params!", EOPENSSL, constparams);
			throw EOPENSSL;
			}
		
		//Generate DSA key
		retVal = DSA_generate_key(pDSAParams);
		if(!retVal)
			{
			PrintErrorInfo("DSA key generation failed!", EOPENSSL, constparams);
			throw EOPENSSL;
			}

		_tprintf(_T("Generated!\n"));
		//Create a key file
		fp = _tfopen(pPrivKeyFile, _T("w"));

		if(!fp)
			{
			PrintErrorInfo("Error creating key file!", EGeneric, constparams);
			throw EOPENSSL;
			}
		
		//Write generated DSA key to the key file
		if(m_bPassword)
			{
			DWORD len = 0;
			len = _tcslen(GetPassword());
			pbPassword = MakeMBCSString(GetPassword(), CP_UTF8, len);
			retVal = PEM_write_DSAPrivateKey(fp, pDSAParams, EVP_des_ede3_cbc(), (unsigned char *) pbPassword, len, NULL, NULL);
			delete pbPassword;
			}
		else if(m_bAsk)
			{
			retVal = PEM_write_DSAPrivateKey(fp, pDSAParams, EVP_des_ede3_cbc(), NULL, 0, NULL, NULL);
			}
		else 
			{
			_tprintf(_T("\n"));
			retVal = PEM_write_DSAPrivateKey(fp, pDSAParams, NULL , NULL, 0, NULL, NULL);
			}

		if(!retVal)
			{
			PrintErrorInfo("Error writing to key file", EOPENSSL, constparams);
			throw EOPENSSL;
			}
		//Free variables
		DSA_free(pDSAParams);
		fclose(fp);
		SYMBIAN_FREE_MEM(pbSeed);

		//Get command prompt handle
		HANDLE hndl = 0;
		hndl = GetStdHandle(STD_OUTPUT_HANDLE);
		_tprintf(_T("\nCreated key: "));
		DWORD bytesWritten;
		WriteConsole(hndl, pPrivKeyFile, wcslen(pPrivKeyFile), &bytesWritten, NULL);
		retFunc = SUCCESS;	

		}
	catch (...)
		{
		//Delete dsa params
		if(pDSAParams)
			{
			DSA_free(pDSAParams);
			}
		if (fp)
			{
			fclose(fp);
			}
		SYMBIAN_FREE_MEM(pbSeed);
		}

	return retFunc;
}