ecc_keygen.c 2.18 KB
Newer Older
filatov's avatar
filatov committed
/*********************************************************************
######################################################################
##
##  Created by: Denis Filatov
##
##  Copyleft (c) 2015
##  This code is provided under the CeCill-C license agreement.
######################################################################
*********************************************************************/
#include "ecc_api.h"
#include <stdio.h>
#include "../cshared/copts.h"
#include "../cshared/cstr.h"

static const char *_outPath = ".";
static int   _outFormat = 0;
static int _certCount = 1;
static int _compressed = 0;

static const char * _o_formats[] = {
	"bin", "hex", "pem", NULL
};

static copt_t options [] = {
	{ "h?", "help",  COPT_HELP, NULL,                 "Print this help page" },
	{ "o",  "out",   COPT_STR, (void*)&_outPath, "Output path [current dir by default]" },
	{ "O", "format", COPT_STRENUM, (void*)_o_formats, "Output format (bin|hex|pem)[binary by default]" },
	{ "n", "count",      COPT_INT, (void*)&_certCount, "Key pair count (1 by default)" },
	{ NULL, NULL, COPT_END, NULL, NULL }
};

int main(int argc, char** argv)
{
	argc = coptions(argc, argv, COPT_HELP_NOVALUES , options);

	if(argc < 1){
		if(argc<0 && (0-argc)<((sizeof(options)/sizeof(options[0]))-1)){
			printf("Unknown option %s\n", argv[0-argc]);
		}
		const char * a = strrchr(argv[0], '/');
		if (a == NULL) a = argv[0];
		coptions_help(stdout, a, COPT_HELP_NOVALUES, options, "<profile> [signer]");
		return -1;
	}
	_outFormat = copts_enum_value(options, 2, _o_formats);

	if(0 == ecc_api_init()){
		char s[1024], *path;
		int len;
		path = cvstrncpy(s, sizeof(s), _outPath, "/", NULL);
		len = s+sizeof(s)-path;
		for(int count = 0; count < _certCount; count++){
			void * key = ecc_api_key_gen(ecdsa_nistp256_with_sha256, aes_128_ccm);
			if(key){
				int nlen = sprintf(path, "key_%03d", count+1);
				cstrncpy(path + nlen, len - nlen, ".prv");
				ecc_api_key_private_save(key, s, _outFormat);
				cstrncpy(path + nlen, len - nlen, ".pub");
				ecc_api_key_public_save(key, s, _outFormat);
				ecc_api_key_free(key);
			}
		}
	}
	ecc_api_done();
	return 0;
}