Esempio n. 1
0
int hash_file(gost_hash_ctx *ctx,char *filename,char *sum,int mode)
	{
	int fd;
	if ((fd=open(filename,mode))<0)
		{
		TINYCLR_SSL_PERROR(filename);
		return 0;
		}
	if (!hash_stream(ctx,fd,sum))
		{
		TINYCLR_SSL_PERROR(filename);
		return 0;
		}	
	close(fd);
	return 1;
	}
int main(int argc, char **argv)
	{
	int i,err=0;
	TINYCLR_SSL_FILE *IN;

	if (argc == 1)
		{
		do_fp(OPENSSL_TYPE__FILE_STDIN);
		}
	else
		{
		for (i=1; i<argc; i++)
			{
			IN=TINYCLR_SSL_FOPEN(argv[i],"r");
			if (IN == NULL)
				{
				TINYCLR_SSL_PERROR(argv[i]);
				err++;
				continue;
				}
			TINYCLR_SSL_PRINTF("SHA(%s)= ",argv[i]);
			do_fp(IN);
			TINYCLR_SSL_FCLOSE(IN);
			}
		}
	TINYCLR_SSL_EXIT(err);
	}
static void dgram_reset_rcv_timeout(BIO *b)
	{
#if defined(SO_RCVTIMEO)
	bio_dgram_data *data = (bio_dgram_data *)b->ptr;

	/* Is a timer active? */
	if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
		{
#ifdef OPENSSL_SYS_WINDOWS
		int timeout = data->socket_timeout.tv_sec * 1000 +
					  data->socket_timeout.tv_usec / 1000;
		if (TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO,
					   (const char*)&timeout, sizeof(timeout)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt"); }
#else
		if ( TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, &(data->socket_timeout),
						sizeof(struct TINYCLR_SSL_TIMEVAL)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt"); }
#endif
		}
#endif
	}
int main()
{
  OPENSSL_DIR_CTX *ctx = NULL;
  const char *result;

  while((result = OPENSSL_DIR_read(&ctx, CURRDIR)) != NULL)
    {
      TINYCLR_SSL_PRINTF("%s\n", result);
    }

  if (errno)
    {
      TINYCLR_SSL_PERROR("test_dir");
      TINYCLR_SSL_EXIT(1);
    }

  if (!OPENSSL_DIR_end(&ctx))
    {
      TINYCLR_SSL_PERROR("test_dir");
      TINYCLR_SSL_EXIT(2);
    }
  TINYCLR_SSL_EXIT(0);
}
Esempio n. 5
0
static X509_CRL *load_crl(char *infile, int format)
	{
	X509_CRL *x=NULL;
	BIO *in=NULL;

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

	if (infile == NULL)
		BIO_set_fp(in,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}
	if 	(format == FORMAT_ASN1)
		x=d2i_X509_CRL_bio(in,NULL);
	else if (format == FORMAT_PEM)
		x=PEM_read_bio_X509_CRL(in,NULL,NULL,NULL);
	else	{
		BIO_printf(bio_err,"bad input format specified for input crl\n");
		goto end;
		}
	if (x == NULL)
		{
		BIO_printf(bio_err,"unable to load CRL\n");
		ERR_print_errors(bio_err);
		goto end;
		}
	
end:
	BIO_free(in);
	return(x);
	}
Esempio n. 6
0
int MAIN(int argc, char **argv)
	{
	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,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT);

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

	argv++;
	argc--;
	for (;;)
		{
		if (argc <= 0) break;
		if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-") == 0)
			goto bad;
#ifndef OPENSSL_NO_DES
		else if (TINYCLR_SSL_STRCMP(*argv,"-des") == 0)
			enc=EVP_des_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-des3") == 0)
			enc=EVP_des_ede3_cbc();
#endif
#ifndef OPENSSL_NO_IDEA
		else if (TINYCLR_SSL_STRCMP(*argv,"-idea") == 0)
			enc=EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
		else if (TINYCLR_SSL_STRCMP(*argv,"-seed") == 0)
			enc=EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes128") == 0)
			enc=EVP_aes_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes192") == 0)
			enc=EVP_aes_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes256") == 0)
			enc=EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia128") == 0)
			enc=EVP_camellia_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia192") == 0)
			enc=EVP_camellia_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia256") == 0)
			enc=EVP_camellia_256_cbc();
#endif
		else if (**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
        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)))
		{
		TINYCLR_SSL_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,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto 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);
	}
Esempio n. 7
0
int MAIN(int argc, char **argv)
	{
	int i,badops=0;
	BIO *in=NULL,*out=NULL;
	int informat,outformat;
	char *infile,*outfile,*prog,*certfile;
	PKCS7 *p7 = NULL;
	PKCS7_SIGNED *p7s = NULL;
	X509_CRL *crl=NULL;
	STACK_OF(OPENSSL_STRING) *certflst=NULL;
	STACK_OF(X509_CRL) *crl_stack=NULL;
	STACK_OF(X509) *cert_stack=NULL;
	int ret=1,nocrl=0;

	apps_startup();

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

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

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-nocrl") == 0)
			{
			nocrl=1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-certfile") == 0)
			{
			if (--argc < 1) goto bad;
			if(!certflst) certflst = sk_OPENSSL_STRING_new_null();
			sk_OPENSSL_STRING_push(certflst,*(++argv));
			}
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] <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," -certfile arg  certificates file of chain to a trusted CA\n");
		BIO_printf(bio_err,"                (can be used more than once)\n");
		BIO_printf(bio_err," -nocrl         no crl to load, just certs from '-certfile'\n");
		ret = 1;
		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 (!nocrl)
		{
		if (infile == NULL)
			BIO_set_fp(in,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
		else
			{
			if (BIO_read_filename(in,infile) <= 0)
				{
				TINYCLR_SSL_PERROR(infile);
				goto end;
				}
			}

		if 	(informat == FORMAT_ASN1)
			crl=d2i_X509_CRL_bio(in,NULL);
		else if (informat == FORMAT_PEM)
			crl=PEM_read_bio_X509_CRL(in,NULL,NULL,NULL);
		else	{
			BIO_printf(bio_err,"bad input format specified for input crl\n");
			goto end;
			}
		if (crl == NULL)
			{
			BIO_printf(bio_err,"unable to load CRL\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		}
	
	if ((p7=PKCS7_new()) == NULL) goto end;
	if ((p7s=PKCS7_SIGNED_new()) == NULL) goto end;
	p7->type=OBJ_nid2obj(NID_pkcs7_signed);
	p7->d.sign=p7s;
	p7s->contents->type=OBJ_nid2obj(NID_pkcs7_data);

	if (!ASN1_INTEGER_set(p7s->version,1)) goto end;
	if ((crl_stack=sk_X509_CRL_new_null()) == NULL) goto end;
	p7s->crl=crl_stack;
	if (crl != NULL)
		{
		sk_X509_CRL_push(crl_stack,crl);
		crl=NULL; /* now part of p7 for OPENSSL_freeing */
		}

	if ((cert_stack=sk_X509_new_null()) == NULL) goto end;
	p7s->cert=cert_stack;

	if(certflst) for(i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) {
		certfile = sk_OPENSSL_STRING_value(certflst, i);
		if (add_certs_from_file(cert_stack,certfile) < 0)
			{
			BIO_printf(bio_err, "error loading certificates\n");
			ERR_print_errors(bio_err);
			goto end;
			}
	}

	sk_OPENSSL_STRING_free(certflst);

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

	if 	(outformat == FORMAT_ASN1)
		i=i2d_PKCS7_bio(out,p7);
	else if (outformat == FORMAT_PEM)
		i=PEM_write_bio_PKCS7(out,p7);
	else	{
		BIO_printf(bio_err,"bad output format specified for outfile\n");
		goto end;
		}
	if (!i)
		{
		BIO_printf(bio_err,"unable to write pkcs7 object\n");
		ERR_print_errors(bio_err);
		goto end;
		}
	ret=0;
end:
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (p7 != NULL) PKCS7_free(p7);
	if (crl != NULL) X509_CRL_free(crl);

	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
	{
	long ret=1;
	int *ip;
	struct TINYCLR_SSL_SOCKADDR *to = NULL;
	bio_dgram_data *data = NULL;
#if defined(IP_MTU_DISCOVER) || defined(IP_MTU)
	long sockopt_val = 0;
	unsigned int sockopt_len = 0;
#endif
#ifdef OPENSSL_SYS_LINUX
	socklen_t addr_len;
	union	{
		struct TINYCLR_SSL_SOCKADDR	sa;
		struct TINYCLR_SSL_SOCKADDR_IN s4;
#if OPENSSL_USE_IPV6
		struct sockaddr_in6 s6;
#endif
		} addr;
#endif

	data = (bio_dgram_data *)b->ptr;

	switch (cmd)
		{
	case BIO_CTRL_RESET:
		num=0;
	case BIO_C_FILE_SEEK:
		ret=0;
		break;
	case BIO_C_FILE_TELL:
	case BIO_CTRL_INFO:
		ret=0;
		break;
	case BIO_C_SET_FD:
		dgram_clear(b);
		b->num= *((int *)ptr);
		b->shutdown=(int)num;
		b->init=1;
		break;
	case BIO_C_GET_FD:
		if (b->init)
			{
			ip=(int *)ptr;
			if (ip != NULL) *ip=b->num;
			ret=b->num;
			}
		else
			ret= -1;
		break;
	case BIO_CTRL_GET_CLOSE:
		ret=b->shutdown;
		break;
	case BIO_CTRL_SET_CLOSE:
		b->shutdown=(int)num;
		break;
	case BIO_CTRL_PENDING:
	case BIO_CTRL_WPENDING:
		ret=0;
		break;
	case BIO_CTRL_DUP:
	case BIO_CTRL_FLUSH:
		ret=1;
		break;
	case BIO_CTRL_DGRAM_CONNECT:
		to = (struct TINYCLR_SSL_SOCKADDR *)ptr;
#if 0
		if (TINYCLR_SSL_CONNECT(b->num, to, sizeof(struct TINYCLR_SSL_SOCKADDR)) < 0)
			{ TINYCLR_SSL_PERROR("connect"); ret = 0; }
		else
			{
#endif
			switch (to->sa_family)
				{
				case AF_INET:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in));
					break;
#if OPENSSL_USE_IPV6
				case AF_INET6:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in6));
					break;
#endif
				default:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa));
					break;
				}
#if 0
			}
#endif
		break;
		/* (Linux)kernel sets DF bit on outgoing IP packets */
	case BIO_CTRL_DGRAM_MTU_DISCOVER:
#ifdef OPENSSL_SYS_LINUX
		addr_len = (socklen_t)sizeof(addr);
		TINYCLR_SSL_MEMSET((void *)&addr, 0, sizeof(addr));
		if (getsockname(b->num, &addr.sa, &addr_len) < 0)
			{
			ret = 0;
			break;
			}
		sockopt_len = sizeof(sockopt_val);
		switch (addr.sa.sa_family)
			{
		case AF_INET:
			sockopt_val = IP_PMTUDISC_DO;
			if ((ret = TINYCLR_SSL_SETSOCKOPT(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
				&sockopt_val, sizeof(sockopt_val))) < 0)
				TINYCLR_SSL_PERROR("setsockopt");
			break;
#if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER)
		case AF_INET6:
			sockopt_val = IPV6_PMTUDISC_DO;
			if ((ret = TINYCLR_SSL_SETSOCKOPT(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
				&sockopt_val, sizeof(sockopt_val))) < 0)
				TINYCLR_SSL_PERROR("setsockopt");
			break;
#endif
		default:
			ret = -1;
			break;
			}
		ret = -1;
#else
		break;
#endif
	case BIO_CTRL_DGRAM_QUERY_MTU:
#ifdef OPENSSL_SYS_LINUX
		addr_len = (socklen_t)sizeof(addr);
		TINYCLR_SSL_MEMSET((void *)&addr, 0, sizeof(addr));
		if (getsockname(b->num, &addr.sa, &addr_len) < 0)
			{
			ret = 0;
			break;
			}
		sockopt_len = sizeof(sockopt_val);
		switch (addr.sa.sa_family)
			{
		case AF_INET:
			if ((ret = TINYCLR_SSL_GETSOCKOPT(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
				&sockopt_len)) < 0 || sockopt_val < 0)
				{
				ret = 0;
				}
			else
				{
				/* we assume that the transport protocol is UDP and no
				 * IP options are used.
				 */
				data->mtu = sockopt_val - 8 - 20;
				ret = data->mtu;
				}
			break;
#if OPENSSL_USE_IPV6 && defined(IPV6_MTU)
		case AF_INET6:
			if ((ret = TINYCLR_SSL_GETSOCKOPT(b->num, IPPROTO_IPV6, IPV6_MTU, (void *)&sockopt_val,
				&sockopt_len)) < 0 || sockopt_val < 0)
				{
				ret = 0;
				}
			else
				{
				/* we assume that the transport protocol is UDP and no
				 * IPV6 options are used.
				 */
				data->mtu = sockopt_val - 8 - 40;
				ret = data->mtu;
				}
			break;
#endif
		default:
			ret = 0;
			break;
			}
#else
		ret = 0;
#endif
		break;
	case BIO_CTRL_DGRAM_GET_MTU:
		return data->mtu;
		break;
	case BIO_CTRL_DGRAM_SET_MTU:
		data->mtu = num;
		ret = num;
		break;
	case BIO_CTRL_DGRAM_SET_CONNECTED:
		to = (struct TINYCLR_SSL_SOCKADDR *)ptr;

		if ( to != NULL)
			{
			data->connected = 1;
			switch (to->sa_family)
				{
				case AF_INET:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in));
					break;
#if OPENSSL_USE_IPV6
				case AF_INET6:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in6));
					break;
#endif
				default:
					TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa));
					break;
				}
			}
		else
			{
			data->connected = 0;
			TINYCLR_SSL_MEMSET(&(data->peer), 0x00, sizeof(data->peer));
			}
		break;
	case BIO_CTRL_DGRAM_GET_PEER:
		switch (data->peer.sa.sa_family)
			{
			case AF_INET:
				ret=sizeof(data->peer.sa_in);
				break;
#if OPENSSL_USE_IPV6
			case AF_INET6:
				ret=sizeof(data->peer.sa_in6);
				break;
#endif
			default:
				ret=sizeof(data->peer.sa);
				break;
			}
		if (num==0 || num>ret)
			num=ret;
		TINYCLR_SSL_MEMCPY(ptr,&data->peer,(ret=num));
		break;
	case BIO_CTRL_DGRAM_SET_PEER:
		to = (struct TINYCLR_SSL_SOCKADDR *) ptr;
		switch (to->sa_family)
			{
			case AF_INET:
				TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in));
				break;
#if OPENSSL_USE_IPV6
			case AF_INET6:
				TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa_in6));
				break;
#endif
			default:
				TINYCLR_SSL_MEMCPY(&data->peer,to,sizeof(data->peer.sa));
				break;
			}
		break;
	case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
		TINYCLR_SSL_MEMCPY(&(data->next_timeout), ptr, sizeof(struct TINYCLR_SSL_TIMEVAL));
		break;
#if defined(SO_RCVTIMEO)
	case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
		{
		struct TINYCLR_SSL_TIMEVAL *tv = (struct TINYCLR_SSL_TIMEVAL *)ptr;
		int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
		if (TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO,
			(const char*)&timeout, sizeof(timeout)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt"); ret = -1; }
		}
#else
		if ( TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
			sizeof(struct TINYCLR_SSL_TIMEVAL)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt");	ret = -1; }
#endif
		break;
	case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
		{
		int timeout, sz = sizeof(timeout);
		struct TINYCLR_SSL_TIMEVAL *tv = (struct TINYCLR_SSL_TIMEVAL *)ptr;
		if (TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO,
			(char*)&timeout, &sz) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
		else
			{
			tv->tv_sec = timeout / 1000;
			tv->tv_usec = (timeout % 1000) * 1000;
			ret = sizeof(*tv);
			}
		}
#elif defined(OPENSSL_SYS_ARM) || defined(OPENSSL_SYS_SH)
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, 
			ptr, (u32_t *)&ret) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
#else
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, 
			ptr, (void *)&ret) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
#endif
		break;
#endif
#if defined(SO_SNDTIMEO)
	case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
		{
		struct TINYCLR_SSL_TIMEVAL *tv = (struct TINYCLR_SSL_TIMEVAL *)ptr;
		int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
		if (TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_SNDTIMEO,
			(const char*)&timeout, sizeof(timeout)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt"); ret = -1; }
		}
#else
		if ( TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
			sizeof(struct TINYCLR_SSL_TIMEVAL)) < 0)
			{ TINYCLR_SSL_PERROR("setsockopt");	ret = -1; }
#endif
		break;
	case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
		{
		int timeout, sz = sizeof(timeout);
		struct TINYCLR_SSL_TIMEVAL *tv = (struct TINYCLR_SSL_TIMEVAL *)ptr;
		if (TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_SNDTIMEO,
			(char*)&timeout, &sz) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
		else
			{
			tv->tv_sec = timeout / 1000;
			tv->tv_usec = (timeout % 1000) * 1000;
			ret = sizeof(*tv);
			}
		}
#elif defined(OPENSSL_SYS_ARM) || defined(OPENSSL_SYS_SH)
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_SNDTIMEO, 
			ptr, (u32_t *)&ret) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
#else
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_SNDTIMEO, 
			ptr, (void *)&ret) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); ret = -1; }
#endif
		break;
#endif
	case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
		/* fall-through */
	case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
#ifdef OPENSSL_SYS_WINDOWS
		if ( data->_errno == WSAETIMEDOUT)
#else
		if ( data->_errno == EAGAIN)
#endif
			{
			ret = 1;
			data->_errno = 0;
			}
		else
			ret = 0;
		break;
#ifdef EMSGSIZE
	case BIO_CTRL_DGRAM_MTU_EXCEEDED:
		if ( data->_errno == EMSGSIZE)
			{
			ret = 1;
			data->_errno = 0;
			}
		else
			ret = 0;
		break;
#endif
	default:
		ret=0;
		break;
		}
	return(ret);
	}
Esempio n. 9
0
int MAIN(int argc, char **argv)
	{
	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,OPENSSL_TYPE__FILE_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 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if(TINYCLR_SSL_STRCMP(*argv, "-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine = *(++argv);
			}
#endif
#ifdef GENCB_TEST
		else if(TINYCLR_SSL_STRCMP(*argv, "-timebomb") == 0)
			{
			if (--argc < 1) goto bad;
			timebomb = atoi(*(++argv));
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-C") == 0)
			C=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-genkey") == 0)
			{
			genkey=1;
			need_rand=1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			need_rand=1;
			}
		else if (TINYCLR_SSL_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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}
	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto end;
			}
		}

#ifndef OPENSSL_NO_ENGINE
        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);
		TINYCLR_SSL_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;

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

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

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

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

		TINYCLR_SSL_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);
	}
Esempio n. 10
0
int MAIN(int argc, char **argv)
	{
	PKCS7 *p7=NULL;
	int i,badops=0;
	BIO *in=NULL,*out=NULL;
	int informat,outformat;
	char *infile,*outfile,*prog;
	int print_certs=0,text=0,noout=0,p7_print=0;
	int ret=1;
#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,OPENSSL_TYPE__FILE_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 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-print") == 0)
			p7_print=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-print_certs") == 0)
			print_certs=1;
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] <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," -print_certs  print any certs or crl in the input\n");
		BIO_printf(bio_err," -text         print full details of certificates\n");
		BIO_printf(bio_err," -noout        don't output encoded data\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e     use engine e, possibly a hardware device.\n");
#endif
		ret = 1;
		goto end;
		}

	ERR_load_crypto_strings();

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

	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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
		if (in == NULL)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}

	if	(informat == FORMAT_ASN1)
		p7=d2i_PKCS7_bio(in,NULL);
	else if (informat == FORMAT_PEM)
		p7=PEM_read_bio_PKCS7(in,NULL,NULL,NULL);
	else
		{
		BIO_printf(bio_err,"bad input format specified for pkcs7 object\n");
		goto end;
		}
	if (p7 == NULL)
		{
		BIO_printf(bio_err,"unable to load PKCS7 object\n");
		ERR_print_errors(bio_err);
		goto end;
		}

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

	if (p7_print)
		PKCS7_print_ctx(out, p7, 0, NULL);

	if (print_certs)
		{
		STACK_OF(X509) *certs=NULL;
		STACK_OF(X509_CRL) *crls=NULL;

		i=OBJ_obj2nid(p7->type);
		switch (i)
			{
		case NID_pkcs7_signed:
			certs=p7->d.sign->cert;
			crls=p7->d.sign->crl;
			break;
		case NID_pkcs7_signedAndEnveloped:
			certs=p7->d.signed_and_enveloped->cert;
			crls=p7->d.signed_and_enveloped->crl;
			break;
		default:
			break;
			}

		if (certs != NULL)
			{
			X509 *x;

			for (i=0; i<sk_X509_num(certs); i++)
				{
				x=sk_X509_value(certs,i);
				if(text) X509_print(out, x);
				else dump_cert_text(out, x);

				if(!noout) PEM_write_bio_X509(out,x);
				BIO_puts(out,"\n");
				}
			}
		if (crls != NULL)
			{
			X509_CRL *crl;

			for (i=0; i<sk_X509_CRL_num(crls); i++)
				{
				crl=sk_X509_CRL_value(crls,i);

				X509_CRL_print(out, crl);

				if(!noout)PEM_write_bio_X509_CRL(out,crl);
				BIO_puts(out,"\n");
				}
			}

		ret=0;
		goto end;
		}

	if(!noout) {
		if 	(outformat == FORMAT_ASN1)
			i=i2d_PKCS7_bio(out,p7);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_PKCS7(out,p7);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}

		if (!i)
			{
			BIO_printf(bio_err,"unable to write pkcs7 object\n");
			ERR_print_errors(bio_err);
			goto end;
			}
	}
	ret=0;
end:
	if (p7 != NULL) PKCS7_free(p7);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
int MAIN(int argc, char **argv)
{
    ENGINE *e = NULL;
    char *infile=NULL, *outfile=NULL, *keyname = NULL;
    char *certfile=NULL;
    BIO *in=NULL, *out = NULL;
    char **args;
    char *name = NULL;
    char *csp_name = NULL;
    int add_lmk = 0;
    PKCS12 *p12 = NULL;
    char pass[50], macpass[50];
    int export_cert = 0;
    int options = 0;
    int chain = 0;
    int badarg = 0;
    int iter = PKCS12_DEFAULT_ITER;
    int maciter = PKCS12_DEFAULT_ITER;
    int twopass = 0;
    int keytype = 0;
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int ret = 1;
    int macver = 1;
    int noprompt = 0;
    STACK_OF(OPENSSL_STRING) *canames = NULL;
    char *cpass = NULL, *mpass = NULL;
    char *passargin = NULL, *passargout = NULL, *passarg = NULL;
    char *passin = NULL, *passout = NULL;
    char *inrand = NULL;
    char *macalg = NULL;
    char *CApath = NULL, *CAfile = NULL;
#ifndef OPENSSL_NO_ENGINE
    char *engine=NULL;
#endif

    apps_startup();

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

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

    args = argv + 1;


    while (*args) {
        if (*args[0] == '-') {
            if (!TINYCLR_SSL_STRCMP (*args, "-nokeys")) options |= NOKEYS;
            else if (!TINYCLR_SSL_STRCMP (*args, "-keyex")) keytype = KEY_EX;
            else if (!TINYCLR_SSL_STRCMP (*args, "-keysig")) keytype = KEY_SIG;
            else if (!TINYCLR_SSL_STRCMP (*args, "-nocerts")) options |= NOCERTS;
            else if (!TINYCLR_SSL_STRCMP (*args, "-clcerts")) options |= CLCERTS;
            else if (!TINYCLR_SSL_STRCMP (*args, "-cacerts")) options |= CACERTS;
            else if (!TINYCLR_SSL_STRCMP (*args, "-noout")) options |= (NOKEYS|NOCERTS);
            else if (!TINYCLR_SSL_STRCMP (*args, "-info")) options |= INFO;
            else if (!TINYCLR_SSL_STRCMP (*args, "-chain")) chain = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-twopass")) twopass = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-nomacver")) macver = 0;
            else if (!TINYCLR_SSL_STRCMP (*args, "-descert"))
                cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
            else if (!TINYCLR_SSL_STRCMP (*args, "-export")) export_cert = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-des")) enc=EVP_des_cbc();
            else if (!TINYCLR_SSL_STRCMP (*args, "-des3")) enc = EVP_des_ede3_cbc();
#ifndef OPENSSL_NO_IDEA
            else if (!TINYCLR_SSL_STRCMP (*args, "-idea")) enc=EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
            else if (!TINYCLR_SSL_STRCMP(*args, "-seed")) enc=EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
            else if (!TINYCLR_SSL_STRCMP(*args,"-aes128")) enc=EVP_aes_128_cbc();
            else if (!TINYCLR_SSL_STRCMP(*args,"-aes192")) enc=EVP_aes_192_cbc();
            else if (!TINYCLR_SSL_STRCMP(*args,"-aes256")) enc=EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
            else if (!TINYCLR_SSL_STRCMP(*args,"-camellia128")) enc=EVP_camellia_128_cbc();
            else if (!TINYCLR_SSL_STRCMP(*args,"-camellia192")) enc=EVP_camellia_192_cbc();
            else if (!TINYCLR_SSL_STRCMP(*args,"-camellia256")) enc=EVP_camellia_256_cbc();
#endif
            else if (!TINYCLR_SSL_STRCMP (*args, "-noiter")) iter = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-maciter"))
                maciter = PKCS12_DEFAULT_ITER;
            else if (!TINYCLR_SSL_STRCMP (*args, "-nomaciter"))
                maciter = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-nomac"))
                maciter = -1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-macalg"))
                if (args[1]) {
                    args++;
                    macalg = *args;
                } else badarg = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-nodes")) enc=NULL;
            else if (!TINYCLR_SSL_STRCMP (*args, "-certpbe")) {
                if (!set_pbe(bio_err, &cert_pbe, *++args))
                    badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-keypbe")) {
                if (!set_pbe(bio_err, &key_pbe, *++args))
                    badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-rand")) {
                if (args[1]) {
                    args++;
                    inrand = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-inkey")) {
                if (args[1]) {
                    args++;
                    keyname = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-certfile")) {
                if (args[1]) {
                    args++;
                    certfile = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-name")) {
                if (args[1]) {
                    args++;
                    name = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-LMK"))
                add_lmk = 1;
            else if (!TINYCLR_SSL_STRCMP (*args, "-CSP")) {
                if (args[1]) {
                    args++;
                    csp_name = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-caname")) {
                if (args[1]) {
                    args++;
                    if (!canames) canames = sk_OPENSSL_STRING_new_null();
                    sk_OPENSSL_STRING_push(canames, *args);
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-in")) {
                if (args[1]) {
                    args++;
                    infile = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-out")) {
                if (args[1]) {
                    args++;
                    outfile = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP(*args,"-passin")) {
                if (args[1]) {
                    args++;
                    passargin = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP(*args,"-passout")) {
                if (args[1]) {
                    args++;
                    passargout = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP (*args, "-password")) {
                if (args[1]) {
                    args++;
                    passarg = *args;
                    noprompt = 1;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP(*args,"-CApath")) {
                if (args[1]) {
                    args++;
                    CApath = *args;
                } else badarg = 1;
            } else if (!TINYCLR_SSL_STRCMP(*args,"-CAfile")) {
                if (args[1]) {
                    args++;
                    CAfile = *args;
                } else badarg = 1;
#ifndef OPENSSL_NO_ENGINE
            } else if (!TINYCLR_SSL_STRCMP(*args,"-engine")) {
                if (args[1]) {
                    args++;
                    engine = *args;
                } else badarg = 1;
#endif
            } else badarg = 1;

        } else badarg = 1;
        args++;
    }

    if (badarg) {
        BIO_printf (bio_err, "Usage: pkcs12 [options]\n");
        BIO_printf (bio_err, "where options are\n");
        BIO_printf (bio_err, "-export       output PKCS12 file\n");
        BIO_printf (bio_err, "-chain        add certificate chain\n");
        BIO_printf (bio_err, "-inkey file   private key if not infile\n");
        BIO_printf (bio_err, "-certfile f   add all certs in f\n");
        BIO_printf (bio_err, "-CApath arg   - PEM format directory of CA's\n");
        BIO_printf (bio_err, "-CAfile arg   - PEM format file of CA's\n");
        BIO_printf (bio_err, "-name \"name\"  use name as friendly name\n");
        BIO_printf (bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
        BIO_printf (bio_err, "-in  infile   input filename\n");
        BIO_printf (bio_err, "-out outfile  output filename\n");
        BIO_printf (bio_err, "-noout        don't output anything, just verify.\n");
        BIO_printf (bio_err, "-nomacver     don't verify MAC.\n");
        BIO_printf (bio_err, "-nocerts      don't output certificates.\n");
        BIO_printf (bio_err, "-clcerts      only output client certificates.\n");
        BIO_printf (bio_err, "-cacerts      only output CA certificates.\n");
        BIO_printf (bio_err, "-nokeys       don't output private keys.\n");
        BIO_printf (bio_err, "-info         give info about PKCS#12 structure.\n");
        BIO_printf (bio_err, "-des          encrypt private keys with DES\n");
        BIO_printf (bio_err, "-des3         encrypt private keys with triple DES (default)\n");
#ifndef OPENSSL_NO_IDEA
        BIO_printf (bio_err, "-idea         encrypt private keys with idea\n");
#endif
#ifndef OPENSSL_NO_SEED
        BIO_printf (bio_err, "-seed         encrypt private keys with seed\n");
#endif
#ifndef OPENSSL_NO_AES
        BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
        BIO_printf (bio_err, "              encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
        BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n");
        BIO_printf (bio_err, "              encrypt PEM output with cbc camellia\n");
#endif
        BIO_printf (bio_err, "-nodes        don't encrypt private keys\n");
        BIO_printf (bio_err, "-noiter       don't use encryption iteration\n");
        BIO_printf (bio_err, "-nomaciter    don't use MAC iteration\n");
        BIO_printf (bio_err, "-maciter      use MAC iteration\n");
        BIO_printf (bio_err, "-nomac        don't generate MAC\n");
        BIO_printf (bio_err, "-twopass      separate MAC, encryption passwords\n");
        BIO_printf (bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
        BIO_printf (bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
        BIO_printf (bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
        BIO_printf (bio_err, "-macalg alg   digest algorithm used in MAC (default SHA1)\n");
        BIO_printf (bio_err, "-keyex        set MS key exchange type\n");
        BIO_printf (bio_err, "-keysig       set MS key signature type\n");
        BIO_printf (bio_err, "-password p   set import/export password source\n");
        BIO_printf (bio_err, "-passin p     input file pass phrase source\n");
        BIO_printf (bio_err, "-passout p    output file pass phrase source\n");
#ifndef OPENSSL_NO_ENGINE
        BIO_printf (bio_err, "-engine e     use engine e, possibly a hardware device.\n");
#endif
        BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
        BIO_printf(bio_err,  "              load the file (or the files in the directory) into\n");
        BIO_printf(bio_err,  "              the random number generator\n");
        BIO_printf(bio_err,  "-CSP name     Microsoft CSP name\n");
        BIO_printf(bio_err,  "-LMK          Add local machine keyset attribute to private key\n");
        goto end;
    }

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

    if(passarg) {
        if(export_cert) passargout = passarg;
        else passargin = passarg;
    }

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

    if(!cpass) {
        if(export_cert) cpass = passout;
        else cpass = passin;
    }

    if(cpass) {
        mpass = cpass;
        noprompt = 1;
    } else {
        cpass = pass;
        mpass = macpass;
    }

    if(export_cert || inrand) {
        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));
    }
    ERR_load_crypto_strings();

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read files");
#endif

    if (!infile) in = BIO_new_fp(OPENSSL_TYPE__FILE_STDIN, BIO_NOCLOSE);
    else in = BIO_new_file(infile, "rb");
    if (!in) {
        BIO_printf(bio_err, "Error opening input file %s\n",
                   infile ? infile : "<OPENSSL_TYPE__FILE_STDIN>");
        TINYCLR_SSL_PERROR (infile);
        goto end;
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
    CRYPTO_push_info("write files");
#endif

    if (!outfile) {
        out = BIO_new_fp(OPENSSL_TYPE__FILE_STDOUT, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
        {
            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
            out = BIO_push(tmpbio, out);
        }
#endif
    } else out = BIO_new_file(outfile, "wb");
    if (!out) {
        BIO_printf(bio_err, "Error opening output file %s\n",
                   outfile ? outfile : "<OPENSSL_TYPE__FILE_STDOUT>");
        TINYCLR_SSL_PERROR (outfile);
        goto end;
    }
    if (twopass) {
#ifdef CRYPTO_MDEBUG
        CRYPTO_push_info("read MAC password");
#endif
        if(EVP_read_pw_string (macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
            goto end;
        }
#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
#endif
    }

    if (export_cert) {
        EVP_PKEY *key = NULL;
        X509 *ucert = NULL, *x = NULL;
        STACK_OF(X509) *certs=NULL;
        const EVP_MD *macmd = NULL;
        unsigned char *catmp = NULL;
        int i;

        if ((options & (NOCERTS|NOKEYS)) == (NOCERTS|NOKEYS))
        {
            BIO_printf(bio_err, "Nothing to do!\n");
            goto export_end;
        }

        if (options & NOCERTS)
            chain = 0;

#ifdef CRYPTO_MDEBUG
        CRYPTO_push_info("process -export_cert");
        CRYPTO_push_info("reading private key");
#endif
        if (!(options & NOKEYS))
        {
            key = load_key(bio_err, keyname ? keyname : infile,
                           FORMAT_PEM, 1, passin, e, "private key");
            if (!key)
                goto export_end;
        }

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("reading certs from input");
#endif

        /* Load in all certs in input file */
        if(!(options & NOCERTS))
        {
            certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
                               "certificates");
            if (!certs)
                goto export_end;

            if (key)
            {
                /* Look for matching private key */
                for(i = 0; i < sk_X509_num(certs); i++)
                {
                    x = sk_X509_value(certs, i);
                    if(X509_check_private_key(x, key))
                    {
                        ucert = x;
                        /* Zero keyid and alias */
                        X509_keyid_set1(ucert, NULL, 0);
                        X509_alias_set1(ucert, NULL, 0);
                        /* Remove from list */
                        (void)sk_X509_delete(certs, i);
                        break;
                    }
                }
                if (!ucert)
                {
                    BIO_printf(bio_err, "No certificate matches private key\n");
                    goto export_end;
                }
            }

        }

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("reading certs from input 2");
#endif

        /* Add any more certificates asked for */
        if(certfile)
        {
            STACK_OF(X509) *morecerts=NULL;
            if(!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
                                        NULL, e,
                                        "certificates from certfile")))
                goto export_end;
            while(sk_X509_num(morecerts) > 0)
                sk_X509_push(certs, sk_X509_shift(morecerts));
            sk_X509_free(morecerts);
        }

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("reading certs from certfile");
#endif

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("building chain");
#endif

        /* If chaining get chain from user cert */
        if (chain) {
            int vret;
            STACK_OF(X509) *chain2;
            X509_STORE *store = X509_STORE_new();
            if (!store)
            {
                BIO_printf (bio_err, "Memory allocation error\n");
                goto export_end;
            }
            if (!X509_STORE_load_locations(store, CAfile, CApath))
                X509_STORE_set_default_paths (store);

            vret = get_cert_chain (ucert, store, &chain2);
            X509_STORE_free(store);

            if (!vret) {
                /* Exclude verified certificate */
                for (i = 1; i < sk_X509_num (chain2) ; i++)
                    sk_X509_push(certs, sk_X509_value (chain2, i));
                /* Free first certificate */
                X509_free(sk_X509_value(chain2, 0));
                sk_X509_free(chain2);
            } else {
                if (vret >= 0)
                    BIO_printf (bio_err, "Error %s getting chain.\n",
                                X509_verify_cert_error_string(vret));
                else
                    ERR_print_errors(bio_err);
                goto export_end;
            }
        }

        /* Add any CA names */

        for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++)
        {
            catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
            X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
        }

        if (csp_name && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
                                      MBSTRING_ASC, (unsigned char *)csp_name, -1);

        if (add_lmk && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("reading password");
#endif

        if(!noprompt &&
                EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
            goto export_end;
        }
        if (!twopass) BUF_strlcpy(macpass, pass, sizeof macpass);

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("creating PKCS#12 structure");
#endif

        p12 = PKCS12_create(cpass, name, key, ucert, certs,
                            key_pbe, cert_pbe, iter, -1, keytype);

        if (!p12)
        {
            ERR_print_errors (bio_err);
            goto export_end;
        }

        if (macalg)
        {
            macmd = EVP_get_digestbyname(macalg);
            if (!macmd)
            {
                BIO_printf(bio_err, "Unknown digest algorithm %s\n",
                           macalg);
            }
        }

        if (maciter != -1)
            PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_push_info("writing pkcs12");
#endif

        i2d_PKCS12_bio(out, p12);

        ret = 0;

export_end:
#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
        CRYPTO_pop_info();
        CRYPTO_push_info("process -export_cert: freeing");
#endif

        if (key) EVP_PKEY_free(key);
        if (certs) sk_X509_pop_free(certs, X509_free);
        if (ucert) X509_free(ucert);

#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
#endif
        goto end;

    }

    if (!(p12 = d2i_PKCS12_bio (in, NULL))) {
        ERR_print_errors(bio_err);
        goto end;
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read import password");
#endif
    if(!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
        goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif

    if (!twopass) BUF_strlcpy(macpass, pass, sizeof macpass);

    if (options & INFO) BIO_printf (bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get (p12->mac->iter) : 1);
    if(macver) {
#ifdef CRYPTO_MDEBUG
        CRYPTO_push_info("verify MAC");
#endif
        /* If we enter empty password try no password first */
        if(!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
            /* If mac and crypto pass the same set it to NULL too */
            if(!twopass) cpass = NULL;
        } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
            BIO_printf (bio_err, "Mac verify error: invalid password?\n");
            ERR_print_errors (bio_err);
            goto end;
        }
        BIO_printf (bio_err, "MAC verified OK\n");
#ifdef CRYPTO_MDEBUG
        CRYPTO_pop_info();
#endif
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("output keys and certificates");
#endif
    if (!dump_certs_keys_p12 (out, p12, cpass, -1, options, passout)) {
        BIO_printf(bio_err, "Error outputting keys and certificates\n");
        ERR_print_errors (bio_err);
        goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    ret = 0;
end:
    if (p12) PKCS12_free(p12);
    if(export_cert || inrand) app_RAND_write_file(NULL, bio_err);
#ifdef CRYPTO_MDEBUG
    CRYPTO_remove_all_info();
#endif
    BIO_free(in);
    BIO_free_all(out);
    if (canames) sk_OPENSSL_STRING_free(canames);
    if(passin) OPENSSL_free(passin);
    if(passout) OPENSSL_free(passout);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Esempio n. 12
0
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	int ret=1;
	RSA *rsa=NULL;
	int i,badops=0, sgckey=0;
	const EVP_CIPHER *enc=NULL;
	BIO *out=NULL;
	int informat,outformat,text=0,check=0,noout=0;
	int pubin = 0, pubout = 0;
	char *infile,*outfile,*prog;
	char *passargin = NULL, *passargout = NULL;
	char *passin = NULL, *passout = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	int modulus=0;

	int pvk_encr = 2;

	apps_startup();

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

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

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

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-sgckey") == 0)
			sgckey=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pubin") == 0)
			pubin=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pubout") == 0)
			pubout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_in") == 0)
			pubin = 2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_out") == 0)
			pubout = 2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-strong") == 0)
			pvk_encr=2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-weak") == 0)
			pvk_encr=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-none") == 0)
			pvk_encr=0;
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-modulus") == 0)
			modulus=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0)
			check=1;
		else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL)
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -inform arg     input format - one of DER NET PEM\n");
		BIO_printf(bio_err," -outform arg    output format - one of DER NET PEM\n");
		BIO_printf(bio_err," -in arg         input file\n");
		BIO_printf(bio_err," -sgckey         Use IIS SGC key format\n");
		BIO_printf(bio_err," -passin arg     input file pass phrase source\n");
		BIO_printf(bio_err," -out arg        output file\n");
		BIO_printf(bio_err," -passout arg    output file pass phrase source\n");
		BIO_printf(bio_err," -des            encrypt PEM output with cbc des\n");
		BIO_printf(bio_err," -des3           encrypt PEM output with ede cbc des using 168 bit key\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err," -idea           encrypt PEM output with cbc idea\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err," -seed           encrypt PEM output with cbc seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err," -aes128, -aes192, -aes256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err," -text           print the key in text\n");
		BIO_printf(bio_err," -noout          don't print key out\n");
		BIO_printf(bio_err," -modulus        print the RSA key modulus\n");
		BIO_printf(bio_err," -check          verify key consistency\n");
		BIO_printf(bio_err," -pubin          expect a public key in input file\n");
		BIO_printf(bio_err," -pubout         output a public key\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
		goto end;
		}

	ERR_load_crypto_strings();

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

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

	if(check && pubin) {
		BIO_printf(bio_err, "Only private keys can be checked\n");
		goto end;
	}

	out=BIO_new(BIO_s_file());

	{
		EVP_PKEY	*pkey;

		if (pubin)
			{
			int tmpformat=-1;
			if (pubin == 2)
				{
				if (informat == FORMAT_PEM)
					tmpformat = FORMAT_PEMRSA;
				else if (informat == FORMAT_ASN1)
					tmpformat = FORMAT_ASN1RSA;
				}
			else if (informat == FORMAT_NETSCAPE && sgckey)
				tmpformat = FORMAT_IISSGC;
			else
				tmpformat = informat;
					
			pkey = load_pubkey(bio_err, infile, tmpformat, 1,
				passin, e, "Public Key");
			}
		else
			pkey = load_key(bio_err, infile,
				(informat == FORMAT_NETSCAPE && sgckey ?
					FORMAT_IISSGC : informat), 1,
				passin, e, "Private Key");

		if (pkey != NULL)
			rsa = EVP_PKEY_get1_RSA(pkey);
		EVP_PKEY_free(pkey);
	}

	if (rsa == NULL)
		{
		ERR_print_errors(bio_err);
		goto end;
		}

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

	if (text) 
		if (!RSA_print(out,rsa,0))
			{
			TINYCLR_SSL_PERROR(outfile);
			ERR_print_errors(bio_err);
			goto end;
			}

	if (modulus)
		{
		BIO_printf(out,"Modulus=");
		BN_print(out,rsa->n);
		BIO_printf(out,"\n");
		}

	if (check)
		{
		int r = RSA_check_key(rsa);

		if (r == 1)
			BIO_printf(out,"RSA key ok\n");
		else if (r == 0)
			{
			unsigned long err;

			while ((err = ERR_peek_error()) != 0 &&
				ERR_GET_LIB(err) == ERR_LIB_RSA &&
				ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
				ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE)
				{
				BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err));
				ERR_get_error(); /* remove e from error stack */
				}
			}
		
		if (r == -1 || ERR_peek_error() != 0) /* should happen only if r == -1 */
			{
			ERR_print_errors(bio_err);
			goto end;
			}
		}
		
	if (noout)
		{
		ret = 0;
		goto end;
		}
	BIO_printf(bio_err,"writing RSA key\n");
	if 	(outformat == FORMAT_ASN1) {
		if(pubout || pubin) 
			{
			if (pubout == 2)
				i=i2d_RSAPublicKey_bio(out,rsa);
			else
				i=i2d_RSA_PUBKEY_bio(out,rsa);
			}
		else i=i2d_RSAPrivateKey_bio(out,rsa);
	}
#ifndef OPENSSL_NO_RC4
	else if (outformat == FORMAT_NETSCAPE)
		{
		unsigned char *p,*pp;
		int size;

		i=1;
		size=i2d_RSA_NET(rsa,NULL,NULL, sgckey);
		if ((p=(unsigned char *)OPENSSL_malloc(size)) == NULL)
			{
			BIO_printf(bio_err,"Memory allocation failure\n");
			goto end;
			}
		pp=p;
		i2d_RSA_NET(rsa,&p,NULL, sgckey);
		BIO_write(out,(char *)pp,size);
		OPENSSL_free(pp);
		}
#endif
	else if (outformat == FORMAT_PEM) {
		if(pubout || pubin)
			{
			if (pubout == 2)
		    		i=PEM_write_bio_RSAPublicKey(out,rsa);
			else
		    		i=PEM_write_bio_RSA_PUBKEY(out,rsa);
			}
		else i=PEM_write_bio_RSAPrivateKey(out,rsa,
						enc,NULL,0,NULL,passout);
#if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
	} else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
		EVP_PKEY *pk;
		pk = EVP_PKEY_new();
		EVP_PKEY_set1_RSA(pk, rsa);
		if (outformat == FORMAT_PVK)
			i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
		else if (pubin || pubout)
			i = i2b_PublicKey_bio(out, pk);
		else
			i = i2b_PrivateKey_bio(out, pk);
		EVP_PKEY_free(pk);
#endif
	} else	{
		BIO_printf(bio_err,"bad output format specified for outfile\n");
		goto end;
		}
	if (i <= 0)
		{
		BIO_printf(bio_err,"unable to write key\n");
		ERR_print_errors(bio_err);
		}
	else
		ret=0;
end:
	if(out != NULL) BIO_free_all(out);
	if(rsa != NULL) RSA_free(rsa);
	if(passin) OPENSSL_free(passin);
	if(passout) OPENSSL_free(passout);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Esempio n. 13
0
int main(int argc,char **argv)
	{
	int c,i;
	int verbose=0;
	int errors=0;
	int open_mode = O_RDONLY;
	gost_subst_block *b=  &GostR3411_94_CryptoProParamSet;
	TINYCLR_SSL_FILE *check_file = NULL;
	gost_hash_ctx ctx;
	
	while( (c=getopt(argc,argv,"bc::tv"))!=-1)
		{
		switch (c)
			{
			case 'v': verbose=1; break;
			case 't': b= &GostR3411_94_TestParamSet; break;
			case 'b': open_mode |= O_BINARY; break;
			case 'c':
				if (optarg)
					{
					check_file = TINYCLR_SSL_FOPEN(optarg,"r");
					if (!check_file)
						{
						TINYCLR_SSL_PERROR(optarg);
						TINYCLR_SSL_EXIT(2);
						}
					}
				else
					{
				  	check_file= OPENSSL_TYPE__FILE_STDIN;
					}
				break;
			default:
				TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"invalid option %c",optopt);
				help();
			}
		}
	init_gost_hash_ctx(&ctx,b);
	if (check_file)
		{
		char inhash[65],calcsum[65],filename[PATH_MAX];
		int failcount=0,count=0;;
		if (check_file==OPENSSL_TYPE__FILE_STDIN && optind<argc)
			{
			check_file=TINYCLR_SSL_FOPEN(argv[optind],"r");
			if (!check_file)
				{	
				TINYCLR_SSL_PERROR(argv[optind]);
				TINYCLR_SSL_EXIT(2);
				}
			}	
		while (get_line(check_file,inhash,filename))
			{
			if (!hash_file(&ctx,filename,calcsum,open_mode))
				{
				TINYCLR_SSL_EXIT (2);
				}	
			count++;
			if (!TINYCLR_SSL_STRNCMP(calcsum,inhash,65))
				{
				if (verbose)
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s\tOK\n",filename);
					}
				}
			else
				{
				if (verbose)
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s\tFAILED\n",filename);
					}
				else
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s: GOST hash sum check failed for '%s'\n",
						argv[0],filename);
					}
				failcount++;
				}
			}	
		if (verbose && failcount)
			{
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s: %d of %d file(f) failed GOST hash sum check\n",
				argv[0],failcount,count);
			}
		TINYCLR_SSL_EXIT (failcount?1:0);
		}
	if (optind==argc)
		{
		char sum[65];
		if (!hash_stream(&ctx,TINYCLR_SSL_FILENO(OPENSSL_TYPE__FILE_STDIN),sum))
			{
			TINYCLR_SSL_PERROR("OPENSSL_TYPE__FILE_STDIN");
			TINYCLR_SSL_EXIT(1);
			}	
		TINYCLR_SSL_PRINTF("%s -\n",sum);
		TINYCLR_SSL_EXIT(0);
		}	
	for (i=optind;i<argc;i++)
		{
		char sum[65];
		if (!hash_file(&ctx,argv[i],sum,open_mode))
			{
			errors++;
			}
		else
			{	
			TINYCLR_SSL_PRINTF("%s %s\n",sum,argv[i]);
			}
		}	
	TINYCLR_SSL_EXIT(errors?1:0);	
	}
Esempio n. 14
0
int main(int argc, char *argv[])
	{
	TINYCLR_SSL_FILE *in=NULL,*out=NULL;
	char *infile=NULL,*outfile=NULL,*keystr=NULL;
	RC4_KEY key;
	char buf[BUFSIZ];
	int badops=0,i;
	char **pp;
	unsigned char md[MD5_DIGEST_LENGTH];

	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-key") == 0)
			{
			if (--argc < 1) goto bad;
			keystr= *(++argv);
			}
		else
			{
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		for (pp=usage; (*pp != NULL); pp++)
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s",*pp);
		TINYCLR_SSL_EXIT(1);
		}

	if (infile == NULL)
		in=OPENSSL_TYPE__FILE_STDIN;
	else
		{
		in=TINYCLR_SSL_FOPEN(infile,"r");
		if (in == NULL)
			{
			TINYCLR_SSL_PERROR("open");
			TINYCLR_SSL_EXIT(1);
			}

		}
	if (outfile == NULL)
		out=OPENSSL_TYPE__FILE_STDOUT;
	else
		{
		out=TINYCLR_SSL_FOPEN(outfile,"w");
		if (out == NULL)
			{
			TINYCLR_SSL_PERROR("open");
			TINYCLR_SSL_EXIT(1);
			}
		}
		
#ifdef OPENSSL_SYS_MSDOS
	/* This should set the file to binary mode. */
	{
#include <fcntl.h>
	setmode(TINYCLR_SSL_FILENO(in),O_BINARY);
	setmode(TINYCLR_SSL_FILENO(out),O_BINARY);
	}
#endif

	if (keystr == NULL)
		{ /* get key */
		i=EVP_read_pw_string(buf,BUFSIZ,"Enter RC4 password:"******"bad password read\n");
			TINYCLR_SSL_EXIT(1);
			}
		keystr=buf;
		}

	EVP_Digest((unsigned char *)keystr,TINYCLR_SSL_STRLEN(keystr),md,NULL,EVP_md5(),NULL);
	OPENSSL_cleanse(keystr,TINYCLR_SSL_STRLEN(keystr));
	RC4_set_key(&key,MD5_DIGEST_LENGTH,md);
	
	for(;;)
		{
		i=TINYCLR_SSL_FREAD(buf,1,BUFSIZ,in);
		if (i == 0) break;
		if (i < 0)
			{
			TINYCLR_SSL_PERROR("read");
			TINYCLR_SSL_EXIT(1);
			}
		RC4(&key,(unsigned int)i,(unsigned char *)buf,
			(unsigned char *)buf);
		i=TINYCLR_SSL_FWRITE(buf,(unsigned int)i,1,out);
		if (i != 1)
			{
			TINYCLR_SSL_PERROR("write");
			TINYCLR_SSL_EXIT(1);
			}
		}
	TINYCLR_SSL_FCLOSE(out);
	TINYCLR_SSL_FCLOSE(in);
	TINYCLR_SSL_EXIT(0);
	return(1);
	}
Esempio n. 15
0
int MAIN(int argc, char **argv)
	{
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	DH *dh=NULL;
	int i,badops=0,text=0;
	BIO *in=NULL,*out=NULL;
	int informat,outformat,check=0,noout=0,C=0,ret=1;
	char *infile,*outfile,*prog;
#ifndef OPENSSL_NO_ENGINE
	char *engine;
#endif

	apps_startup();

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

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

#ifndef OPENSSL_NO_ENGINE
	engine=NULL;
#endif
	infile=NULL;
	outfile=NULL;
	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0)
			check=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-C") == 0)
			C=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout=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] <infile >outfile\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -inform arg   input format - one of DER PEM\n");
		BIO_printf(bio_err," -outform arg  output format - one of DER PEM\n");
		BIO_printf(bio_err," -in arg       input file\n");
		BIO_printf(bio_err," -out arg      output file\n");
		BIO_printf(bio_err," -check        check the DH parameters\n");
		BIO_printf(bio_err," -text         print a text form of the DH parameters\n");
		BIO_printf(bio_err," -C            Output C code\n");
		BIO_printf(bio_err," -noout        no output\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e     use engine e, possibly a hardware device.\n");
#endif
		goto end;
		}

	ERR_load_crypto_strings();

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

	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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}
	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto end;
			}
		}

	if	(informat == FORMAT_ASN1)
		dh=d2i_DHparams_bio(in,NULL);
	else if (informat == FORMAT_PEM)
		dh=PEM_read_bio_DHparams(in,NULL,NULL,NULL);
	else
		{
		BIO_printf(bio_err,"bad input format specified\n");
		goto end;
		}
	if (dh == NULL)
		{
		BIO_printf(bio_err,"unable to load DH parameters\n");
		ERR_print_errors(bio_err);
		goto end;
		}

	

	if (text)
		{
		DHparams_print(out,dh);
#ifdef undef
		TINYCLR_SSL_PRINTF("p=");
		BN_print(OPENSSL_TYPE__FILE_STDOUT,dh->p);
		TINYCLR_SSL_PRINTF("\ng=");
		BN_print(OPENSSL_TYPE__FILE_STDOUT,dh->g);
		TINYCLR_SSL_PRINTF("\n");
		if (dh->length != 0)
			TINYCLR_SSL_PRINTF("recommended private length=%ld\n",dh->length);
#endif
		}
	
	if (check)
		{
		if (!DH_check(dh,&i))
			{
			ERR_print_errors(bio_err);
			goto end;
			}
		if (i & DH_CHECK_P_NOT_PRIME)
			TINYCLR_SSL_PRINTF("p value is not prime\n");
		if (i & DH_CHECK_P_NOT_SAFE_PRIME)
			TINYCLR_SSL_PRINTF("p value is not a safe prime\n");
		if (i & DH_UNABLE_TO_CHECK_GENERATOR)
			TINYCLR_SSL_PRINTF("unable to check the generator value\n");
		if (i & DH_NOT_SUITABLE_GENERATOR)
			TINYCLR_SSL_PRINTF("the g value is not a generator\n");
		if (i == 0)
			TINYCLR_SSL_PRINTF("DH parameters appear to be ok.\n");
		}
	if (C)
		{
		unsigned char *data;
		int len,l,bits;

		len=BN_num_bytes(dh->p);
		bits=BN_num_bits(dh->p);
		data=(unsigned char *)OPENSSL_malloc(len);
		if (data == NULL)
			{
			TINYCLR_SSL_PERROR("OPENSSL_malloc");
			goto end;
			}
		l=BN_bn2bin(dh->p,data);
		TINYCLR_SSL_PRINTF("static unsigned char dh%d_p[]={",bits);
		for (i=0; i<l; i++)
			{
			if ((i%12) == 0) TINYCLR_SSL_PRINTF("\n\t");
			TINYCLR_SSL_PRINTF("0x%02X,",data[i]);
			}
		TINYCLR_SSL_PRINTF("\n\t};\n");

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

		TINYCLR_SSL_PRINTF("DH *get_dh%d()\n\t{\n",bits);
		TINYCLR_SSL_PRINTF("\tDH *dh;\n\n");
		TINYCLR_SSL_PRINTF("\tif ((dh=DH_new()) == NULL) return(NULL);\n");
		TINYCLR_SSL_PRINTF("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n",
			bits,bits);
		TINYCLR_SSL_PRINTF("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n",
			bits,bits);
		TINYCLR_SSL_PRINTF("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
		TINYCLR_SSL_PRINTF("\t\treturn(NULL);\n");
		TINYCLR_SSL_PRINTF("\treturn(dh);\n\t}\n");
		OPENSSL_free(data);
		}


	if (!noout)
		{
		if 	(outformat == FORMAT_ASN1)
			i=i2d_DHparams_bio(out,dh);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_DHparams(out,dh);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		if (!i)
			{
			BIO_printf(bio_err,"unable to write DH parameters\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		}
	ret=0;
end:
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (dh != NULL) DH_free(dh);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Esempio n. 16
0
int MAIN(int argc, char **argv)
{
    ENGINE *e = NULL;
    int ret=1;
    DSA *dsa=NULL;
    int i,badops=0;
    const EVP_CIPHER *enc=NULL;
    BIO *in=NULL,*out=NULL;
    int informat,outformat,text=0,noout=0;
    int pubin = 0, pubout = 0;
    char *infile,*outfile,*prog;
#ifndef OPENSSL_NO_ENGINE
    char *engine;
#endif
    char *passargin = NULL, *passargout = NULL;
    char *passin = NULL, *passout = NULL;
    int modulus=0;

    int pvk_encr = 2;

    apps_startup();

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

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

#ifndef OPENSSL_NO_ENGINE
    engine=NULL;
#endif
    infile=NULL;
    outfile=NULL;
    informat=FORMAT_PEM;
    outformat=FORMAT_PEM;

    prog=argv[0];
    argc--;
    argv++;
    while (argc >= 1)
    {
        if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
        {
            if (--argc < 1) goto bad;
            informat=str2fmt(*(++argv));
        }
        else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
        {
            if (--argc < 1) goto bad;
            outformat=str2fmt(*(++argv));
        }
        else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
        {
            if (--argc < 1) goto bad;
            infile= *(++argv);
        }
        else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
        {
            if (--argc < 1) goto bad;
            outfile= *(++argv);
        }
        else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0)
        {
            if (--argc < 1) goto bad;
            passargin= *(++argv);
        }
        else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
        {
            if (--argc < 1) goto bad;
            passargout= *(++argv);
        }
#ifndef OPENSSL_NO_ENGINE
        else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
        {
            if (--argc < 1) goto bad;
            engine= *(++argv);
        }
#endif
        else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-strong") == 0)
            pvk_encr=2;
        else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-weak") == 0)
            pvk_encr=1;
        else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-none") == 0)
            pvk_encr=0;
        else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
            noout=1;
        else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
            text=1;
        else if (TINYCLR_SSL_STRCMP(*argv,"-modulus") == 0)
            modulus=1;
        else if (TINYCLR_SSL_STRCMP(*argv,"-pubin") == 0)
            pubin=1;
        else if (TINYCLR_SSL_STRCMP(*argv,"-pubout") == 0)
            pubout=1;
        else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL)
        {
            BIO_printf(bio_err,"unknown option %s\n",*argv);
            badops=1;
            break;
        }
        argc--;
        argv++;
    }

    if (badops)
    {
bad:
        BIO_printf(bio_err,"%s [options] <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," -passin arg     input file pass phrase source\n");
        BIO_printf(bio_err," -out arg        output file\n");
        BIO_printf(bio_err," -passout arg    output file pass phrase source\n");
#ifndef OPENSSL_NO_ENGINE
        BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
        BIO_printf(bio_err," -des            encrypt PEM output with cbc des\n");
        BIO_printf(bio_err," -des3           encrypt PEM output with ede cbc des using 168 bit key\n");
#ifndef OPENSSL_NO_IDEA
        BIO_printf(bio_err," -idea           encrypt PEM output with cbc idea\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_SEED
        BIO_printf(bio_err," -seed           encrypt PEM output with cbc seed\n");
#endif
        BIO_printf(bio_err," -text           print the key in text\n");
        BIO_printf(bio_err," -noout          don't print key out\n");
        BIO_printf(bio_err," -modulus        print the DSA public value\n");
        goto end;
    }

    ERR_load_crypto_strings();

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

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

    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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
    else
    {
        if (BIO_read_filename(in,infile) <= 0)
        {
            TINYCLR_SSL_PERROR(infile);
            goto end;
        }
    }

    BIO_printf(bio_err,"read DSA key\n");

    {
        EVP_PKEY	*pkey;

        if (pubin)
            pkey = load_pubkey(bio_err, infile, informat, 1,
                               passin, e, "Public Key");
        else
            pkey = load_key(bio_err, infile, informat, 1,
                            passin, e, "Private Key");

        if (pkey)
        {
            dsa = EVP_PKEY_get1_DSA(pkey);
            EVP_PKEY_free(pkey);
        }
    }
    if (dsa == NULL)
    {
        BIO_printf(bio_err,"unable to load Key\n");
        ERR_print_errors(bio_err);
        goto end;
    }

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

    if (text)
        if (!DSA_print(out,dsa,0))
        {
            TINYCLR_SSL_PERROR(outfile);
            ERR_print_errors(bio_err);
            goto end;
        }

    if (modulus)
    {
        TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDOUT,"Public Key=");
        BN_print(out,dsa->pub_key);
        TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDOUT,"\n");
    }

    if (noout) goto end;
    BIO_printf(bio_err,"writing DSA key\n");
    if 	(outformat == FORMAT_ASN1) {
        if(pubin || pubout) i=i2d_DSA_PUBKEY_bio(out,dsa);
        else i=i2d_DSAPrivateKey_bio(out,dsa);
    } else if (outformat == FORMAT_PEM) {
        if(pubin || pubout)
            i=PEM_write_bio_DSA_PUBKEY(out,dsa);
        else i=PEM_write_bio_DSAPrivateKey(out,dsa,enc,
                                               NULL,0,NULL, passout);
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_RC4)
    } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
        EVP_PKEY *pk;
        pk = EVP_PKEY_new();
        EVP_PKEY_set1_DSA(pk, dsa);
        if (outformat == FORMAT_PVK)
            i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
        else if (pubin || pubout)
            i = i2b_PublicKey_bio(out, pk);
        else
            i = i2b_PrivateKey_bio(out, pk);
        EVP_PKEY_free(pk);
#endif
    } else {
        BIO_printf(bio_err,"bad output format specified for outfile\n");
        goto end;
    }
    if (i <= 0)
    {
        BIO_printf(bio_err,"unable to write private key\n");
        ERR_print_errors(bio_err);
    }
    else
        ret=0;
end:
    if(in != NULL) BIO_free(in);
    if(out != NULL) BIO_free_all(out);
    if(dsa != NULL) DSA_free(dsa);
    if(passin) OPENSSL_free(passin);
    if(passout) OPENSSL_free(passout);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Esempio n. 17
0
int MAIN(int argc, char **argv)
	{
	unsigned long nmflag = 0;
	X509_CRL *x=NULL;
	char *CAfile = NULL, *CApath = NULL;
	int ret=1,i,num,badops=0;
	BIO *out=NULL;
	int informat,outformat;
	char *infile=NULL,*outfile=NULL;
	int hash=0,issuer=0,lastupdate=0,nextupdate=0,noout=0,text=0;
	int fingerprint = 0, crlnumber = 0;
	const char **pp;
	X509_STORE *store = NULL;
	X509_STORE_CTX ctx;
	X509_LOOKUP *lookup = NULL;
	X509_OBJECT xobj;
	EVP_PKEY *pkey;
	int do_ver = 0;
	const EVP_MD *md_alg,*digest=EVP_sha1();

	apps_startup();

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

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

	if (bio_out == NULL)
		if ((bio_out=BIO_new(BIO_s_file())) != NULL)
			{
			BIO_set_fp(bio_out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
			{
			BIO *tmpbio = BIO_new(BIO_f_linebuffer());
			bio_out = BIO_push(tmpbio, bio_out);
			}
#endif
			}

	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	argc--;
	argv++;
	num=0;
	while (argc >= 1)
		{
#ifdef undef
		if	(TINYCLR_SSL_STRCMP(*argv,"-p") == 0)
			{
			if (--argc < 1) goto bad;
			if (!args_from_file(++argv,Nargc,Nargv)) { goto end; }*/
			}
#endif
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-CApath") == 0)
			{
			if (--argc < 1) goto bad;
			CApath = *(++argv);
			do_ver = 1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-CAfile") == 0)
			{
			if (--argc < 1) goto bad;
			CAfile = *(++argv);
			do_ver = 1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-verify") == 0)
			do_ver = 1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text = 1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-hash") == 0)
			hash= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-nameopt") == 0)
			{
			if (--argc < 1) goto bad;
			if (!set_name_ex(&nmflag, *(++argv))) goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-issuer") == 0)
			issuer= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-lastupdate") == 0)
			lastupdate= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-nextupdate") == 0)
			nextupdate= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-fingerprint") == 0)
			fingerprint= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-crlnumber") == 0)
			crlnumber= ++num;
		else if ((md_alg=EVP_get_digestbyname(*argv + 1)))
			{
			/* ok */
			digest=md_alg;
			}
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		for (pp=crl_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);
		goto end;
		}

	ERR_load_crypto_strings();
	x=load_crl(infile,informat);
	if (x == NULL) { goto end; }

	if(do_ver) {
		store = X509_STORE_new();
		lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
		if (lookup == NULL) goto end;
		if (!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM))
			X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
			
		lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
		if (lookup == NULL) goto end;
		if (!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM))
			X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
		ERR_clear_error();

		if(!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) {
			BIO_printf(bio_err,
				"Error initialising X509 store\n");
			goto end;
		}

		i = X509_STORE_get_by_subject(&ctx, X509_LU_X509, 
					X509_CRL_get_issuer(x), &xobj);
		if(i <= 0) {
			BIO_printf(bio_err,
				"Error getting CRL issuer certificate\n");
			goto end;
		}
		pkey = X509_get_pubkey(xobj.data.x509);
		X509_OBJECT_free_contents(&xobj);
		if(!pkey) {
			BIO_printf(bio_err,
				"Error getting CRL issuer public key\n");
			goto end;
		}
		i = X509_CRL_verify(x, pkey);
		EVP_PKEY_free(pkey);
		if(i < 0) goto end;
		if(i == 0) BIO_printf(bio_err, "verify failure\n");
		else BIO_printf(bio_err, "verify OK\n");
	}

	if (num)
		{
		for (i=1; i<=num; i++)
			{
			if (issuer == i)
				{
				print_name(bio_out, "issuer=", X509_CRL_get_issuer(x), nmflag);
				}
			if (crlnumber == i)
				{
				ASN1_INTEGER *crlnum;
				crlnum = (ASN1_INTEGER*)X509_CRL_get_ext_d2i(x, NID_crl_number,
							      NULL, NULL);
				BIO_printf(bio_out,"crlNumber=");
				if (crlnum)
					{
					i2a_ASN1_INTEGER(bio_out, crlnum);
					ASN1_INTEGER_free(crlnum);
					}
				else
					BIO_puts(bio_out, "<NONE>");
				BIO_printf(bio_out,"\n");
				}
			if (hash == i)
				{
				BIO_printf(bio_out,"%08lx\n",
					X509_NAME_hash(X509_CRL_get_issuer(x)));
				}
			if (lastupdate == i)
				{
				BIO_printf(bio_out,"lastUpdate=");
				ASN1_TIME_print(bio_out,
						X509_CRL_get_lastUpdate(x));
				BIO_printf(bio_out,"\n");
				}
			if (nextupdate == i)
				{
				BIO_printf(bio_out,"nextUpdate=");
				if (X509_CRL_get_nextUpdate(x)) 
					ASN1_TIME_print(bio_out,
						X509_CRL_get_nextUpdate(x));
				else
					BIO_printf(bio_out,"NONE");
				BIO_printf(bio_out,"\n");
				}
			if (fingerprint == i)
				{
				int j;
				unsigned int n;
				unsigned char md[EVP_MAX_MD_SIZE];

				if (!X509_CRL_digest(x,digest,md,&n))
					{
					BIO_printf(bio_err,"out of memory\n");
					goto end;
					}
				BIO_printf(bio_out,"%s Fingerprint=",
						OBJ_nid2sn(EVP_MD_type(digest)));
				for (j=0; j<(int)n; j++)
					{
					BIO_printf(bio_out,"%02X%c",md[j],
						(j+1 == (int)n)
						?'\n':':');
					}
				}
			}
		}

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

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

	if (text) X509_CRL_print(out, x);

	if (noout) 
		{
		ret = 0;
		goto end;
		}

	if 	(outformat == FORMAT_ASN1)
		i=(int)i2d_X509_CRL_bio(out,x);
	else if (outformat == FORMAT_PEM)
		i=PEM_write_bio_X509_CRL(out,x);
	else	
		{
		BIO_printf(bio_err,"bad output format specified for outfile\n");
		goto end;
		}
	if (!i) { BIO_printf(bio_err,"unable to write CRL\n"); goto end; }
	ret=0;
end:
	BIO_free_all(out);
	BIO_free_all(bio_out);
	bio_out=NULL;
	X509_CRL_free(x);
	if(store) {
		X509_STORE_CTX_cleanup(&ctx);
		X509_STORE_free(store);
	}
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Esempio n. 18
0
int MAIN(int argc, char **argv)
	{
	int i,badops=0,offset=0,ret=1,j;
	unsigned int length=0;
	long num,tmplen;
	BIO *in=NULL,*out=NULL,*b64=NULL, *derout = NULL;
	int informat,indent=0, noout = 0, dump = 0;
	char *infile=NULL,*str=NULL,*prog,*oidfile=NULL, *derfile=NULL;
	char *genstr=NULL, *genconf=NULL;
	unsigned char *tmpbuf;
	const unsigned char *ctmpbuf;
	BUF_MEM *buf=NULL;
	STACK_OF(OPENSSL_STRING) *osk=NULL;
	ASN1_TYPE *at=NULL;

	informat=FORMAT_PEM;

	apps_startup();

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

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

	prog=argv[0];
	argc--;
	argv++;
	if ((osk=sk_OPENSSL_STRING_new_null()) == NULL)
		{
		BIO_printf(bio_err,"Memory allocation failure\n");
		goto end;
		}
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			derfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-i") == 0)
			{
			indent=1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0) noout = 1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-oid") == 0)
			{
			if (--argc < 1) goto bad;
			oidfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-offset") == 0)
			{
			if (--argc < 1) goto bad;
			offset= atoi(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-length") == 0)
			{
			if (--argc < 1) goto bad;
			length= atoi(*(++argv));
			if (length == 0) goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-dump") == 0)
			{
			dump= -1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-dlimit") == 0)
			{
			if (--argc < 1) goto bad;
			dump= atoi(*(++argv));
			if (dump <= 0) goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-strparse") == 0)
			{
			if (--argc < 1) goto bad;
			sk_OPENSSL_STRING_push(osk,*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-genstr") == 0)
			{
			if (--argc < 1) goto bad;
			genstr= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-genconf") == 0)
			{
			if (--argc < 1) goto bad;
			genconf= *(++argv);
			}
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] <infile\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -inform arg   input format - one of DER PEM\n");
		BIO_printf(bio_err," -in arg       input file\n");
		BIO_printf(bio_err," -out arg      output file (output format is always DER\n");
		BIO_printf(bio_err," -noout arg    don't produce any output\n");
		BIO_printf(bio_err," -offset arg   offset into file\n");
		BIO_printf(bio_err," -length arg   length of section in file\n");
		BIO_printf(bio_err," -i            indent entries\n");
		BIO_printf(bio_err," -dump         dump unknown data in hex form\n");
		BIO_printf(bio_err," -dlimit arg   dump the first arg bytes of unknown data in hex form\n");
		BIO_printf(bio_err," -oid file     file of extra oid definitions\n");
		BIO_printf(bio_err," -strparse offset\n");
		BIO_printf(bio_err,"               a series of these can be used to 'dig' into multiple\n");
		BIO_printf(bio_err,"               ASN1 blob wrappings\n");
		BIO_printf(bio_err," -genstr str   string to generate ASN1 structure from\n");
		BIO_printf(bio_err," -genconf file file to generate ASN1 structure from\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;
		}
	BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE|BIO_FP_TEXT);
#ifdef OPENSSL_SYS_VMS
	{
	BIO *tmpbio = BIO_new(BIO_f_linebuffer());
	out = BIO_push(tmpbio, out);
	}
#endif

	if (oidfile != NULL)
		{
		if (BIO_read_filename(in,oidfile) <= 0)
			{
			BIO_printf(bio_err,"problems opening %s\n",oidfile);
			ERR_print_errors(bio_err);
			goto end;
			}
		OBJ_create_objects(in);
		}

	if (infile == NULL)
		BIO_set_fp(in,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}

	if (derfile) {
		if(!(derout = BIO_new_file(derfile, "wb"))) {
			BIO_printf(bio_err,"problems opening %s\n",derfile);
			ERR_print_errors(bio_err);
			goto end;
		}
	}

	if ((buf=BUF_MEM_new()) == NULL) goto end;
	if (!BUF_MEM_grow(buf,BUFSIZ*8)) goto end; /* Pre-allocate :-) */

	if (genstr || genconf)
		{
		num = do_generate(bio_err, genstr, genconf, buf);
		if (num < 0)
			{
			ERR_print_errors(bio_err);
			goto end;
			}
		}

	else
		{

		if (informat == FORMAT_PEM)
			{
			BIO *tmp;

			if ((b64=BIO_new(BIO_f_base64())) == NULL)
				goto end;
			BIO_push(b64,in);
			tmp=in;
			in=b64;
			b64=tmp;
			}

		num=0;
		for (;;)
			{
			if (!BUF_MEM_grow(buf,(int)num+BUFSIZ)) goto end;
			i=BIO_read(in,&(buf->data[num]),BUFSIZ);
			if (i <= 0) break;
			num+=i;
			}
		}
	str=buf->data;

	/* If any structs to parse go through in sequence */

	if (sk_OPENSSL_STRING_num(osk))
		{
		tmpbuf=(unsigned char *)str;
		tmplen=num;
		for (i=0; i<sk_OPENSSL_STRING_num(osk); i++)
			{
			ASN1_TYPE *atmp;
			int typ;
			j=atoi(sk_OPENSSL_STRING_value(osk,i));
			if (j == 0)
				{
				BIO_printf(bio_err,"'%s' is an invalid number\n",sk_OPENSSL_STRING_value(osk,i));
				continue;
				}
			tmpbuf+=j;
			tmplen-=j;
			atmp = at;
			ctmpbuf = tmpbuf;
			at = d2i_ASN1_TYPE(NULL,&ctmpbuf,tmplen);
			ASN1_TYPE_free(atmp);
			if(!at)
				{
				BIO_printf(bio_err,"Error parsing structure\n");
				ERR_print_errors(bio_err);
				goto end;
				}
			typ = ASN1_TYPE_get(at);
			if ((typ == V_ASN1_OBJECT)
				|| (typ == V_ASN1_NULL))
				{
				BIO_printf(bio_err, "Can't parse %s type\n",
					typ == V_ASN1_NULL ? "NULL" : "OBJECT");
				ERR_print_errors(bio_err);
				goto end;
				}
			/* hmm... this is a little evil but it works */
			tmpbuf=at->value.asn1_string->data;
			tmplen=at->value.asn1_string->length;
			}
		str=(char *)tmpbuf;
		num=tmplen;
		}

	if (offset >= num)
		{
		BIO_printf(bio_err, "Error: offset too large\n");
		goto end;
		}

	num -= offset;

	if ((length == 0) || ((long)length > num)) length=(unsigned int)num;
	if(derout) {
		if(BIO_write(derout, str + offset, length) != (int)length) {
			BIO_printf(bio_err, "Error writing output\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (!noout &&
	    !ASN1_parse_dump(out,(unsigned char *)&(str[offset]),length,
		    indent,dump))
		{
		ERR_print_errors(bio_err);
		goto end;
		}
	ret=0;
end:
	BIO_free(derout);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (b64 != NULL) BIO_free(b64);
	if (ret != 0)
		ERR_print_errors(bio_err);
	if (buf != NULL) BUF_MEM_free(buf);
	if (at != NULL) ASN1_TYPE_free(at);
	if (osk != NULL) sk_OPENSSL_STRING_free(osk);
	OBJ_cleanup();
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Esempio n. 19
0
int MAIN(int argc, char **argv)
{
#ifndef OPENSSL_NO_ENGINE
	ENGINE 	*e = NULL;
#endif
	int 	ret = 1;
	EC_KEY 	*eckey = NULL;
	const EC_GROUP *group;
	int 	i, badops = 0;
	const EVP_CIPHER *enc = NULL;
	BIO 	*in = NULL, *out = NULL;
	int 	informat, outformat, text=0, noout=0;
	int  	pubin = 0, pubout = 0, param_out = 0;
	char 	*infile, *outfile, *prog, *engine;
	char 	*passargin = NULL, *passargout = NULL;
	char 	*passin = NULL, *passout = NULL;
	point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
	int	new_form = 0;
	int	asn1_flag = OPENSSL_EC_NAMED_CURVE;
	int 	new_asn1_flag = 0;

	apps_startup();

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

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

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

	prog = argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if (TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-noout") == 0)
			noout = 1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-text") == 0)
			text = 1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-conv_form") == 0)
			{
			if (--argc < 1)
				goto bad;
			++argv;
			new_form = 1;
			if (TINYCLR_SSL_STRCMP(*argv, "compressed") == 0)
				form = POINT_CONVERSION_COMPRESSED;
			else if (TINYCLR_SSL_STRCMP(*argv, "uncompressed") == 0)
				form = POINT_CONVERSION_UNCOMPRESSED;
			else if (TINYCLR_SSL_STRCMP(*argv, "hybrid") == 0)
				form = POINT_CONVERSION_HYBRID;
			else
				goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-param_enc") == 0)
			{
			if (--argc < 1)
				goto bad;
			++argv;
			new_asn1_flag = 1;
			if (TINYCLR_SSL_STRCMP(*argv, "named_curve") == 0)
				asn1_flag = OPENSSL_EC_NAMED_CURVE;
			else if (TINYCLR_SSL_STRCMP(*argv, "explicit") == 0)
				asn1_flag = 0;
			else
				goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-param_out") == 0)
			param_out = 1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-pubin") == 0)
			pubin=1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-pubout") == 0)
			pubout=1;
		else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL)
			{
			BIO_printf(bio_err, "unknown option %s\n", *argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err, "%s [options] <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, " -passin arg     input file pass "
				"phrase source\n");
		BIO_printf(bio_err, " -out arg        output file\n");
		BIO_printf(bio_err, " -passout arg    output file pass "
				"phrase source\n");
		BIO_printf(bio_err, " -engine e       use engine e, "
				"possibly a hardware device.\n");
		BIO_printf(bio_err, " -des            encrypt PEM output, "
				"instead of 'des' every other \n"
				"                 cipher "
				"supported by OpenSSL can be used\n");
		BIO_printf(bio_err, " -text           print the key\n");
		BIO_printf(bio_err, " -noout          don't print key out\n");
		BIO_printf(bio_err, " -param_out      print the elliptic "
				"curve parameters\n");
		BIO_printf(bio_err, " -conv_form arg  specifies the "
				"point conversion form \n");
		BIO_printf(bio_err, "                 possible values:"
				" compressed\n");
		BIO_printf(bio_err, "                                 "
				" uncompressed (default)\n");
		BIO_printf(bio_err, "                                  "
				" hybrid\n");
		BIO_printf(bio_err, " -param_enc arg  specifies the way"
				" the ec parameters are encoded\n");
		BIO_printf(bio_err, "                 in the asn1 der "
				"encoding\n");
		BIO_printf(bio_err, "                 possible values:"
				" named_curve (default)\n");
		BIO_printf(bio_err,"                                  "
				"explicit\n");
		goto end;
		}

	ERR_load_crypto_strings();

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

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

	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, OPENSSL_TYPE__FILE_STDIN, BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in, infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}

	BIO_printf(bio_err, "read EC key\n");
	if (informat == FORMAT_ASN1) 
		{
		if (pubin) 
			eckey = d2i_EC_PUBKEY_bio(in, NULL);
		else 
			eckey = d2i_ECPrivateKey_bio(in, NULL);
		} 
	else if (informat == FORMAT_PEM) 
		{
		if (pubin) 
			eckey = PEM_read_bio_EC_PUBKEY(in, NULL, NULL, 
				NULL);
		else 
			eckey = PEM_read_bio_ECPrivateKey(in, NULL, NULL,
				passin);
		} 
	else
		{
		BIO_printf(bio_err, "bad input format specified for key\n");
		goto end;
		}
	if (eckey == NULL)
		{
		BIO_printf(bio_err,"unable to load Key\n");
		ERR_print_errors(bio_err);
		goto end;
		}

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

	group = EC_KEY_get0_group(eckey);

	if (new_form)
		EC_KEY_set_conv_form(eckey, form);

	if (new_asn1_flag)
		EC_KEY_set_asn1_flag(eckey, asn1_flag);

	if (text) 
		if (!EC_KEY_print(out, eckey, 0))
			{
			TINYCLR_SSL_PERROR(outfile);
			ERR_print_errors(bio_err);
			goto end;
			}

	if (noout) 
		{
		ret = 0;
		goto end;
		}

	BIO_printf(bio_err, "writing EC key\n");
	if (outformat == FORMAT_ASN1) 
		{
		if (param_out)
			i = i2d_ECPKParameters_bio(out, group);
		else if (pubin || pubout) 
			i = i2d_EC_PUBKEY_bio(out, eckey);
		else 
			i = i2d_ECPrivateKey_bio(out, eckey);
		} 
	else if (outformat == FORMAT_PEM) 
		{
		if (param_out)
			i = PEM_write_bio_ECPKParameters(out, group);
		else if (pubin || pubout)
			i = PEM_write_bio_EC_PUBKEY(out, eckey);
		else 
			i = PEM_write_bio_ECPrivateKey(out, eckey, enc,
						NULL, 0, NULL, passout);
		} 
	else 
		{
		BIO_printf(bio_err, "bad output format specified for "
			"outfile\n");
		goto end;
		}

	if (!i)
		{
		BIO_printf(bio_err, "unable to write private key\n");
		ERR_print_errors(bio_err);
		}
	else
		ret=0;
end:
	if (in)
		BIO_free(in);
	if (out)
		BIO_free_all(out);
	if (eckey)
		EC_KEY_free(eckey);
	if (passin)
		OPENSSL_free(passin);
	if (passout)
		OPENSSL_free(passout);
	apps_shutdown();
	OPENSSL_EXIT(ret);
}
Esempio n. 20
0
int MAIN(int argc, char **argv)
	{
	BN_GENCB cb;
	DH *dh=NULL;
	int ret=1,num=DEFBITS;
	int g=2;
	char *outfile=NULL;
	char *inrand=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	BIO *out=NULL;

	apps_startup();

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

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

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

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

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

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

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

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

	if (!PEM_write_bio_DHparams(out,dh))
		goto end;
	ret=0;
end:
	if (ret != 0)
		ERR_print_errors(bio_err);
	if (out != NULL) BIO_free_all(out);
	if (dh != NULL) DH_free(dh);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Esempio n. 21
0
int MAIN(int argc, char **argv)
	{
	SSL_SESSION *x=NULL;
	int ret=1,i,num,badops=0;
	BIO *out=NULL;
	int informat,outformat;
	char *infile=NULL,*outfile=NULL,*context=NULL;
	int cert=0,noout=0,text=0;
	const char **pp;

	apps_startup();

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

	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	argc--;
	argv++;
	num=0;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-cert") == 0)
			cert= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout= ++num;
		else if (TINYCLR_SSL_STRCMP(*argv,"-context") == 0)
		    {
		    if(--argc < 1) goto bad;
		    context=*++argv;
		    }
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		for (pp=sess_id_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);
		goto end;
		}

	ERR_load_crypto_strings();
	x=load_sess_id(infile,informat);
	if (x == NULL) { goto end; }

	if(context)
	    {
	    x->sid_ctx_length=TINYCLR_SSL_STRLEN(context);
	    if(x->sid_ctx_length > SSL_MAX_SID_CTX_LENGTH)
		{
		BIO_printf(bio_err,"Context too long\n");
		goto end;
		}
	    TINYCLR_SSL_MEMCPY(x->sid_ctx,context,x->sid_ctx_length);
	    }

#ifdef undef
	/* just testing for memory leaks :-) */
	{
	SSL_SESSION *s;
	char buf[1024*10],*p;
	int i;

	s=SSL_SESSION_new();

	p= &buf;
	i=i2d_SSL_SESSION(x,&p);
	p= &buf;
	d2i_SSL_SESSION(&s,&p,(long)i);
	p= &buf;
	d2i_SSL_SESSION(&s,&p,(long)i);
	p= &buf;
	d2i_SSL_SESSION(&s,&p,(long)i);
	SSL_SESSION_free(s);
	}
#endif

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

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

	if (text)
		{
		SSL_SESSION_print(out,x);

		if (cert)
			{
			if (x->peer == NULL)
				BIO_puts(out,"No certificate present\n");
			else
				X509_print(out,x->peer);
			}
		}

	if (!noout && !cert)
		{
		if 	(outformat == FORMAT_ASN1)
			i=i2d_SSL_SESSION_bio(out,x);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_SSL_SESSION(out,x);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		if (!i) {
			BIO_printf(bio_err,"unable to write SSL_SESSION\n");
			goto end;
			}
		}
	else if (!noout && (x->peer != NULL)) /* just print the certificate */
		{
		if 	(outformat == FORMAT_ASN1)
			i=(int)i2d_X509_bio(out,x->peer);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_X509(out,x->peer);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		if (!i) {
			BIO_printf(bio_err,"unable to write X509\n");
			goto end;
			}
		}
	ret=0;
end:
	if (out != NULL) BIO_free_all(out);
	if (x != NULL) SSL_SESSION_free(x);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
int MAIN(int argc, char **argv)
	{
	EC_GROUP *group = NULL;
	point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED; 
	int 	new_form = 0;
	int 	asn1_flag = OPENSSL_EC_NAMED_CURVE;
	int 	new_asn1_flag = 0;
	char 	*curve_name = NULL, *inrand = NULL;
	int	list_curves = 0, no_seed = 0, check = 0,
		badops = 0, text = 0, i, need_rand = 0, genkey = 0;
	char	*infile = NULL, *outfile = NULL, *prog;
	BIO 	*in = NULL, *out = NULL;
	int 	informat, outformat, noout = 0, C = 0, ret = 1;
#ifndef OPENSSL_NO_ENGINE
	ENGINE	*e = NULL;
#endif
	char	*engine = NULL;

	BIGNUM	*ec_p = NULL, *ec_a = NULL, *ec_b = NULL,
		*ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL;
	unsigned char *buffer = NULL;

	apps_startup();

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

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

	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text = 1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-C") == 0)
			C = 1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0)
			check = 1;
		else if (TINYCLR_SSL_STRCMP (*argv, "-name") == 0)
			{
			if (--argc < 1)
				goto bad;
			curve_name = *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-list_curves") == 0)
			list_curves = 1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-conv_form") == 0)
			{
			if (--argc < 1)
				goto bad;
			++argv;
			new_form = 1;
			if (TINYCLR_SSL_STRCMP(*argv, "compressed") == 0)
				form = POINT_CONVERSION_COMPRESSED;
			else if (TINYCLR_SSL_STRCMP(*argv, "uncompressed") == 0)
				form = POINT_CONVERSION_UNCOMPRESSED;
			else if (TINYCLR_SSL_STRCMP(*argv, "hybrid") == 0)
				form = POINT_CONVERSION_HYBRID;
			else
				goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-param_enc") == 0)
			{
			if (--argc < 1)
				goto bad;
			++argv;
			new_asn1_flag = 1;
			if (TINYCLR_SSL_STRCMP(*argv, "named_curve") == 0)
				asn1_flag = OPENSSL_EC_NAMED_CURVE;
			else if (TINYCLR_SSL_STRCMP(*argv, "explicit") == 0)
				asn1_flag = 0;
			else
				goto bad;
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-no_seed") == 0)
			no_seed = 1;
		else if (TINYCLR_SSL_STRCMP(*argv, "-noout") == 0)
			noout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-genkey") == 0)
			{
			genkey=1;
			need_rand=1;
			}
		else if (TINYCLR_SSL_STRCMP(*argv, "-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			need_rand=1;
			}
		else if(TINYCLR_SSL_STRCMP(*argv, "-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine = *(++argv);
			}	
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err, "%s [options] <infile >outfile\n",prog);
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, " -inform arg       input format - "
				"default PEM (DER or PEM)\n");
		BIO_printf(bio_err, " -outform arg      output format - "
				"default PEM\n");
		BIO_printf(bio_err, " -in  arg          input file  - "
				"default OPENSSL_TYPE__FILE_STDIN\n");
		BIO_printf(bio_err, " -out arg          output file - "
				"default OPENSSL_TYPE__FILE_STDOUT\n");
		BIO_printf(bio_err, " -noout            do not print the "
				"ec parameter\n");
		BIO_printf(bio_err, " -text             print the ec "
				"parameters in text form\n");
		BIO_printf(bio_err, " -check            validate the ec "
				"parameters\n");
		BIO_printf(bio_err, " -C                print a 'C' "
				"function creating the parameters\n");
		BIO_printf(bio_err, " -name arg         use the "
				"ec parameters with 'short name' name\n");
		BIO_printf(bio_err, " -list_curves      prints a list of "
				"all currently available curve 'short names'\n");
		BIO_printf(bio_err, " -conv_form arg    specifies the "
				"point conversion form \n");
		BIO_printf(bio_err, "                   possible values:"
				" compressed\n");
		BIO_printf(bio_err, "                                   "
				" uncompressed (default)\n");
		BIO_printf(bio_err, "                                   "
				" hybrid\n");
		BIO_printf(bio_err, " -param_enc arg    specifies the way"
				" the ec parameters are encoded\n");
		BIO_printf(bio_err, "                   in the asn1 der "
				"encoding\n");
		BIO_printf(bio_err, "                   possible values:"
				" named_curve (default)\n");
		BIO_printf(bio_err, "                                   "
				" explicit\n");
		BIO_printf(bio_err, " -no_seed          if 'explicit'"
				" parameters are choosen do not"
				" use the seed\n");
		BIO_printf(bio_err, " -genkey           generate ec"
				" key\n");
		BIO_printf(bio_err, " -rand file        files to use for"
				" random number input\n");
		BIO_printf(bio_err, " -engine e         use engine e, "
				"possibly a hardware device\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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,infile) <= 0)
			{
			TINYCLR_SSL_PERROR(infile);
			goto end;
			}
		}
	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto end;
			}
		}

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

	if (list_curves)
		{
		EC_builtin_curve *curves = NULL;
		size_t crv_len = 0;
		size_t n = 0;

		crv_len = EC_get_builtin_curves(NULL, 0);

		curves = (EC_builtin_curve*)OPENSSL_malloc((int)(sizeof(EC_builtin_curve) * crv_len));

		if (curves == NULL)
			goto end;

		if (!EC_get_builtin_curves(curves, crv_len))
			{
			OPENSSL_free(curves);
			goto end;
			}

		
		for (n = 0; n < crv_len; n++)
			{
			const char *comment;
			const char *sname;
			comment = curves[n].comment;
			sname   = OBJ_nid2sn(curves[n].nid);
			if (comment == NULL)
				comment = "CURVE DESCRIPTION NOT AVAILABLE";
			if (sname == NULL)
				sname = "";

			BIO_printf(out, "  %-10s: ", sname);
			BIO_printf(out, "%s\n", comment);
			} 

		OPENSSL_free(curves);
		ret = 0;
		goto end;
		}

	if (curve_name != NULL)
		{
		int nid;

		/* workaround for the SECG curve names secp192r1
		 * and secp256r1 (which are the same as the curves
		 * prime192v1 and prime256v1 defined in X9.62)
		 */
		if (!TINYCLR_SSL_STRCMP(curve_name, "secp192r1"))
			{
			BIO_printf(bio_err, "using curve name prime192v1 "
				"instead of secp192r1\n");
			nid = NID_X9_62_prime192v1;
			}
		else if (!TINYCLR_SSL_STRCMP(curve_name, "secp256r1"))
			{
			BIO_printf(bio_err, "using curve name prime256v1 "
				"instead of secp256r1\n");
			nid = NID_X9_62_prime256v1;
			}
		else
			nid = OBJ_sn2nid(curve_name);
	
		if (nid == 0)
			{
			BIO_printf(bio_err, "unknown curve name (%s)\n", 
				curve_name);
			goto end;
			}

		group = EC_GROUP_new_by_curve_name(nid);
		if (group == NULL)
			{
			BIO_printf(bio_err, "unable to create curve (%s)\n", 
				curve_name);
			goto end;
			}
		EC_GROUP_set_asn1_flag(group, asn1_flag);
		EC_GROUP_set_point_conversion_form(group, form);
		}
	else if (informat == FORMAT_ASN1)
		{
		group = d2i_ECPKParameters_bio(in, NULL);
		}
	else if (informat == FORMAT_PEM)
		{
		group = PEM_read_bio_ECPKParameters(in,NULL,NULL,NULL);
		}
	else
		{
		BIO_printf(bio_err, "bad input format specified\n");
		goto end;
		}

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

	if (new_form)
		EC_GROUP_set_point_conversion_form(group, form);

	if (new_asn1_flag)
		EC_GROUP_set_asn1_flag(group, asn1_flag);

	if (no_seed)
		{
		EC_GROUP_set_seed(group, NULL, 0);
		}

	if (text)
		{
		if (!ECPKParameters_print(out, group, 0))
			goto end;
		}

	if (check)
		{
		if (group == NULL)
			BIO_printf(bio_err, "no elliptic curve parameters\n");
		BIO_printf(bio_err, "checking elliptic curve parameters: ");
		if (!EC_GROUP_check(group, NULL))
			{
			BIO_printf(bio_err, "failed\n");
			ERR_print_errors(bio_err);
			}
		else
			BIO_printf(bio_err, "ok\n");
			
		}

	if (C)
		{
		size_t	buf_len = 0, tmp_len = 0;
		const EC_POINT *point;
		int	is_prime, len = 0;
		const EC_METHOD *meth = EC_GROUP_method_of(group);

		if ((ec_p = BN_new()) == NULL || (ec_a = BN_new()) == NULL ||
		    (ec_b = BN_new()) == NULL || (ec_gen = BN_new()) == NULL ||
		    (ec_order = BN_new()) == NULL || 
		    (ec_cofactor = BN_new()) == NULL )
			{
			TINYCLR_SSL_PERROR("OPENSSL_malloc");
			goto end;
			}

		is_prime = (EC_METHOD_get_field_type(meth) == 
			NID_X9_62_prime_field);

		if (is_prime)
			{
			if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a,
				ec_b, NULL))
				goto end;
			}
		else
			{
			/* TODO */
			goto end;
			}

		if ((point = EC_GROUP_get0_generator(group)) == NULL)
			goto end;
		if (!EC_POINT_point2bn(group, point, 
			EC_GROUP_get_point_conversion_form(group), ec_gen, 
			NULL))
			goto end;
		if (!EC_GROUP_get_order(group, ec_order, NULL))
			goto end;
		if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
			goto end;

		if (!ec_p || !ec_a || !ec_b || !ec_gen || 
			!ec_order || !ec_cofactor)
			goto end;

		len = BN_num_bits(ec_order);

		if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len)
			buf_len = tmp_len;
		if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len)
			buf_len = tmp_len;
		if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len)
			buf_len = tmp_len;
		if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len)
			buf_len = tmp_len;
		if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len)
			buf_len = tmp_len;
		if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len)
			buf_len = tmp_len;

		buffer = (unsigned char *)OPENSSL_malloc(buf_len);

		if (buffer == NULL)
			{
			TINYCLR_SSL_PERROR("OPENSSL_malloc");
			goto end;
			}

		ecparam_print_var(out, ec_p, "ec_p", len, buffer);
		ecparam_print_var(out, ec_a, "ec_a", len, buffer);
		ecparam_print_var(out, ec_b, "ec_b", len, buffer);
		ecparam_print_var(out, ec_gen, "ec_gen", len, buffer);
		ecparam_print_var(out, ec_order, "ec_order", len, buffer);
		ecparam_print_var(out, ec_cofactor, "ec_cofactor", len, 
			buffer);

		BIO_printf(out, "\n\n");

		BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n\t{\n", len);
		BIO_printf(out, "\tint ok=0;\n");
		BIO_printf(out, "\tEC_GROUP *group = NULL;\n");
		BIO_printf(out, "\tEC_POINT *point = NULL;\n");
		BIO_printf(out, "\tBIGNUM   *tmp_1 = NULL, *tmp_2 = NULL, "
				"*tmp_3 = NULL;\n\n");
		BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_p_%d, "
				"sizeof(ec_p_%d), NULL)) == NULL)\n\t\t"
				"goto err;\n", len, len);
		BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_a_%d, "
				"sizeof(ec_a_%d), NULL)) == NULL)\n\t\t"
				"goto err;\n", len, len);
		BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_b_%d, "
				"sizeof(ec_b_%d), NULL)) == NULL)\n\t\t"
				"goto err;\n", len, len);
		if (is_prime)
			{
			BIO_printf(out, "\tif ((group = EC_GROUP_new_curve_"
				"GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)"
				"\n\t\tgoto err;\n\n");
			}
		else
			{
			/* TODO */
			goto end;
			}
		BIO_printf(out, "\t/* build generator */\n");
		BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_gen_%d, "
				"sizeof(ec_gen_%d), tmp_1)) == NULL)"
				"\n\t\tgoto err;\n", len, len);
		BIO_printf(out, "\tpoint = EC_POINT_bn2point(group, tmp_1, "
				"NULL, NULL);\n");
		BIO_printf(out, "\tif (point == NULL)\n\t\tgoto err;\n");
		BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_order_%d, "
				"sizeof(ec_order_%d), tmp_2)) == NULL)"
				"\n\t\tgoto err;\n", len, len);
		BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_cofactor_%d, "
				"sizeof(ec_cofactor_%d), tmp_3)) == NULL)"
				"\n\t\tgoto err;\n", len, len);
		BIO_printf(out, "\tif (!EC_GROUP_set_generator(group, point,"
				" tmp_2, tmp_3))\n\t\tgoto err;\n");
		BIO_printf(out, "\n\tok=1;\n");
		BIO_printf(out, "err:\n");
		BIO_printf(out, "\tif (tmp_1)\n\t\tBN_free(tmp_1);\n");
		BIO_printf(out, "\tif (tmp_2)\n\t\tBN_free(tmp_2);\n");
		BIO_printf(out, "\tif (tmp_3)\n\t\tBN_free(tmp_3);\n");
		BIO_printf(out, "\tif (point)\n\t\tEC_POINT_free(point);\n");
		BIO_printf(out, "\tif (!ok)\n");
		BIO_printf(out, "\t\t{\n");
		BIO_printf(out, "\t\tEC_GROUP_free(group);\n");
		BIO_printf(out, "\t\tgroup = NULL;\n");
		BIO_printf(out, "\t\t}\n");
		BIO_printf(out, "\treturn(group);\n\t}\n");
	}

	if (!noout)
		{
		if (outformat == FORMAT_ASN1)
			i = i2d_ECPKParameters_bio(out, group);
		else if (outformat == FORMAT_PEM)
			i = PEM_write_bio_ECPKParameters(out, group);
		else	
			{
			BIO_printf(bio_err,"bad output format specified for"
				" outfile\n");
			goto end;
			}
		if (!i)
			{
			BIO_printf(bio_err, "unable to write elliptic "
				"curve parameters\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		}
	
	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 (genkey)
		{
		EC_KEY *eckey = EC_KEY_new();

		if (eckey == NULL)
			goto end;

		TINYCLR_SSL_ASSERT(need_rand);

		if (EC_KEY_set_group(eckey, group) == 0)
			goto end;
		
		if (!EC_KEY_generate_key(eckey))
			{
			EC_KEY_free(eckey);
			goto end;
			}
		if (outformat == FORMAT_ASN1)
			i = i2d_ECPrivateKey_bio(out, eckey);
		else if (outformat == FORMAT_PEM)
			i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
				NULL, 0, NULL, NULL);
		else	
			{
			BIO_printf(bio_err, "bad output format specified "
				"for outfile\n");
			EC_KEY_free(eckey);
			goto end;
			}
		EC_KEY_free(eckey);
		}

	if (need_rand)
		app_RAND_write_file(NULL, bio_err);

	ret=0;
end:
	if (ec_p)
		BN_free(ec_p);
	if (ec_a)
		BN_free(ec_a);
	if (ec_b)
		BN_free(ec_b);
	if (ec_gen)
		BN_free(ec_gen);
	if (ec_order)
		BN_free(ec_order);
	if (ec_cofactor)
		BN_free(ec_cofactor);
	if (buffer)
		OPENSSL_free(buffer);
	if (in != NULL)
		BIO_free(in);
	if (out != NULL)
		BIO_free_all(out);
	if (group != NULL)
		EC_GROUP_free(group);
	apps_shutdown();
	OPENSSL_EXIT(ret);
}
int MAIN(int argc, char **argv)
	{
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	DH *dh=NULL;
	int i,badops=0,text=0;
#ifndef OPENSSL_NO_DSA
	int dsaparam=0;
#endif
	BIO *in=NULL,*out=NULL;
	int informat,outformat,check=0,noout=0,C=0,ret=1;
	char *infile,*outfile,*prog;
	char *inrand=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	int num = 0, g = 0;

	apps_startup();

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

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

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

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

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

	ERR_load_crypto_strings();

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

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

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

	if(num) {

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

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

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

		app_RAND_write_file(NULL, bio_err);
	} else {

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

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

#ifndef OPENSSL_NO_DSA
		if (dsaparam)
			{
			DSA *dsa;
			
			if (informat == FORMAT_ASN1)
				dsa=d2i_DSAparams_bio(in,NULL);
			else /* informat == FORMAT_PEM */
				dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL);
			
			if (dsa == NULL)
				{
				BIO_printf(bio_err,"unable to load DSA parameters\n");
				ERR_print_errors(bio_err);
				goto end;
				}
			
			dh = DSA_dup_DH(dsa);
			DSA_free(dsa);
			if (dh == NULL)
				{
				ERR_print_errors(bio_err);
				goto end;
				}
			}
		else
#endif
			{
			if (informat == FORMAT_ASN1)
				dh=d2i_DHparams_bio(in,NULL);
			else /* informat == FORMAT_PEM */
				dh=PEM_read_bio_DHparams(in,NULL,NULL,NULL);
			
			if (dh == NULL)
				{
				BIO_printf(bio_err,"unable to load DH parameters\n");
				ERR_print_errors(bio_err);
				goto end;
				}
			}
		
		/* dh != NULL */
	}
	
	out=BIO_new(BIO_s_file());
	if (out == NULL)
		{
		ERR_print_errors(bio_err);
		goto end;
		}
	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto end;
			}
		}


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

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

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

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

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


	if (!noout)
		{
		if 	(outformat == FORMAT_ASN1)
			i=i2d_DHparams_bio(out,dh);
		else if (outformat == FORMAT_PEM)
			i=PEM_write_bio_DHparams(out,dh);
		else	{
			BIO_printf(bio_err,"bad output format specified for outfile\n");
			goto end;
			}
		if (!i)
			{
			BIO_printf(bio_err,"unable to write DH parameters\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		}
	ret=0;
end:
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (dh != NULL) DH_free(dh);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
int MAIN(int argc, char **argv)
	{
	BN_GENCB cb;
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	int ret=1;
	int i,num=DEFBITS;
	long l;
	const EVP_CIPHER *enc=NULL;
	unsigned long f4=RSA_F4;
	char *outfile=NULL;
	char *passargout = NULL, *passout = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	char *inrand=NULL;
	BIO *out=NULL;
	BIGNUM *bn = BN_new();
	RSA *rsa = NULL;

	if(!bn) goto err;

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

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

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

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

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

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

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

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

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

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

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

	ret=0;
err:
	if (bn) BN_free(bn);
	if (rsa) RSA_free(rsa);
	if (out) BIO_free_all(out);
	if(passout) OPENSSL_free(passout);
	if (ret != 0)
		ERR_print_errors(bio_err);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
static void dgram_adjust_rcv_timeout(BIO *b)
	{
#if defined(SO_RCVTIMEO)
	bio_dgram_data *data = (bio_dgram_data *)b->ptr;
	int sz = sizeof(int);

	/* Is a timer active? */
	if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
		{
		struct TINYCLR_SSL_TIMEVAL timenow, timeleft;

		/* Read current socket timeout */
#ifdef OPENSSL_SYS_WINDOWS
		int timeout;
		if (TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO,
					   (char*)&timeout, &sz) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); }
		else
			{
			data->socket_timeout.tv_sec = timeout / 1000;
			data->socket_timeout.tv_usec = (timeout % 1000) * 1000;
			}
#elif defined(OPENSSL_SYS_ARM) || defined(OPENSSL_SYS_SH)
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, 
						&(data->socket_timeout), (u32_t *)&sz) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); }
#else
		if ( TINYCLR_SSL_GETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, 
						&(data->socket_timeout), (void *)&sz) < 0)
			{ TINYCLR_SSL_PERROR("getsockopt"); }
#endif

		/* Get current time */
		get_current_time(&timenow);

		/* Calculate time left until timer expires */
		TINYCLR_SSL_MEMCPY(&timeleft, &(data->next_timeout), sizeof(struct TINYCLR_SSL_TIMEVAL));
		timeleft.tv_sec -= timenow.tv_sec;
		timeleft.tv_usec -= timenow.tv_usec;
		if (timeleft.tv_usec < 0)
			{
			timeleft.tv_sec--;
			timeleft.tv_usec += 1000000;
			}

		if (timeleft.tv_sec < 0)
			{
			timeleft.tv_sec = 0;
			timeleft.tv_usec = 1;
			}

		/* Adjust socket timeout if next handhake message timer
		 * will expire earlier.
		 */
		if ((data->socket_timeout.tv_sec == 0 && data->socket_timeout.tv_usec == 0) ||
			(data->socket_timeout.tv_sec > timeleft.tv_sec) ||
			(data->socket_timeout.tv_sec == timeleft.tv_sec &&
			 data->socket_timeout.tv_usec >= timeleft.tv_usec))
			{
#ifdef OPENSSL_SYS_WINDOWS
			timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000;
			if (TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO,
						   (const char*)&timeout, sizeof(timeout)) < 0)
				{ TINYCLR_SSL_PERROR("setsockopt"); }
#else
			if ( TINYCLR_SSL_SETSOCKOPT(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft,
							sizeof(struct TINYCLR_SSL_TIMEVAL)) < 0)
				{ TINYCLR_SSL_PERROR("setsockopt"); }
#endif
			}
		}
#endif
	}