ECDSA example


/* This program is released under the Common Public License V1.0
 *
 * You should have received a copy of Common Public License V1.0 along with
 * with this program.
 *
 * Copyright IBM Corp. 2018
 */
#include <errno.h>
#include <openssl/crypto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>

#include <openssl/opensslconf.h>
#ifdef OPENSSL_FIPS
#include <openssl/fips.h>
#endif /* OPENSSL_FIPS */

#include "ica_api.h"
#include "testcase.h"
#include <openssl/obj_mac.h>

#define MAX_ECC_PRIV_SIZE		66 /* 521 bits */
#define MAX_ECDSA_SIG_SIZE		2*MAX_ECC_PRIV_SIZE

static unsigned char hash[] = {
	0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
	0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
	0x10, 0x11, 0x12, 0x13, 
};

int main(int argc, char **argv)
{
	ica_adapter_handle_t adapter_handle;
	unsigned int rc;
	unsigned char signature[MAX_ECDSA_SIG_SIZE];
	unsigned int privlen = 0;
	unsigned int hash_length = 20;
	unsigned int nid = NID_X9_62_prime256v1;
	ICA_EC_KEY *eckey;


	rc = ica_open_adapter(&adapter_handle);
	if (rc != 0) {
		V_(printf("ica_open_adapter failed and returned %d (0x%x).\n", rc, rc));
	}

	eckey = ica_ec_key_new(nid, &privlen);
	if (!eckey) {
		printf("Unsupported curve.\n");
		return rc;
	}

	rc = ica_ec_key_generate(adapter_handle, eckey);
	if (rc) {
		printf("EC key for curve %i could not be generated, rc=%i.\n", nid, rc);
		return rc;
	}

	rc = ica_ecdsa_sign(adapter_handle, eckey, hash, hash_length,
					signature, MAX_ECDSA_SIG_SIZE);
	if (rc) {
		printf("Error creating ECDSA signature for curve %i, rc=%i.\n", nid, rc);
		return rc;
	}

	rc = ica_ecdsa_verify(adapter_handle, eckey, hash, hash_length,
			signature, MAX_ECDSA_SIG_SIZE);
	switch (rc) {
	case 0:
		printf("Signature verified ok.\n");
		break;
	case EINVAL:
		printf("At least one invalid parameter given.\n");
		break;
	case EFAULT:
		printf("Signature is invalid.\n");
		break;
	default:
		printf("An internal processing error occurred.\n");
		break;
	}

	ica_close_adapter(adapter_handle);

	return rc;
}