Commit 1fadbf4b authored by filatov's avatar filatov
Browse files

fix lading zeroes in PubKey generation

parent febd809b
Loading
Loading
Loading
Loading
+33 −15
Original line number Original line Diff line number Diff line
@@ -21,6 +21,7 @@


#define ARRAYSIZE(A) (sizeof(A)/sizeof(A[0]))
#define ARRAYSIZE(A) (sizeof(A)/sizeof(A[0]))


static char * _bin2hex(char * hex, int hlen, const char * bin, int blen);
typedef struct {
typedef struct {
	int nid;
	int nid;
	const char * name;
	const char * name;
@@ -105,7 +106,6 @@ void * ecc_api_key_gen(ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg)
		if (key){
		if (key){
			EC_KEY_set_group(key, _curves[pk_alg]);
			EC_KEY_set_group(key, _curves[pk_alg]);
			EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE);
			EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE);

			if (!EC_KEY_generate_key(key)){
			if (!EC_KEY_generate_key(key)){
				ERR_print_errors_fp(stderr);
				ERR_print_errors_fp(stderr);
				fflush(stderr);
				fflush(stderr);
@@ -215,24 +215,21 @@ int ecc_api_key_private_save(void* key, const char* path, ecc_format format)
				const BIGNUM   * ecbn;
				const BIGNUM   * ecbn;
				ecbn = EC_KEY_get0_private_key(eckey);
				ecbn = EC_KEY_get0_private_key(eckey);
				if (ecbn){
				if (ecbn){
					char * buf = NULL;
					int bnlen = BN_num_bytes(ecbn);
					int len = BN_num_bytes(ecbn);
					int len = (bnlen < 32) ? 32 : bnlen;
					if (format == ecc_bin){
					char * buf = (char *)OPENSSL_malloc(len*2+1);
						buf = (char *)OPENSSL_malloc(len);
					if (bnlen < len) memset(buf, 0, len - bnlen);
						BN_bn2bin(ecbn, (unsigned char *)buf);
					BN_bn2bin(ecbn, (unsigned char *)(buf + len - bnlen));
						rc = 0;
					if (format == ecc_hex){
					}
						char * c = _bin2hex(buf, len * 2 + 1, buf, len);
					else if (format == ecc_hex){
						*c = 0;
						buf = BN_bn2hex(ecbn);
						len = c - buf;
						len = strlen(buf);
						rc = 0;
						rc = 0;
					}
					}
					if (buf){
					rc = (len == fwrite(buf, 1, len, f)) ? 0 : -1;
					rc = (len == fwrite(buf, 1, len, f)) ? 0 : -1;
					OPENSSL_free(buf);
					OPENSSL_free(buf);
				}
				}
			}
			}
			}
			fclose(f);
			fclose(f);
			if (rc < 0){
			if (rc < 0){
				ERR_print_errors_fp(stderr);
				ERR_print_errors_fp(stderr);
@@ -465,3 +462,24 @@ int ecc_sign(void * key, const char * data, int length, char ** psig, int max
	}
	}
	return -1;
	return -1;
}
}


static const char* _hexDigits = "0123456789ABCDEF";
static char * _bin2hex(char * hex, int hlen, const char * bin, int blen)
{
	const unsigned char *b, *e;
	char * s;

	// sanity check
	if (hlen >= 0 && hlen < blen * 2) return NULL;

	b = (const unsigned char *)bin;
	e = b + blen - 1;
	s = hex + blen * 2;
	if (s < hex + hlen) *s = 0;
	for (; b <= e; e--){
		*(--s) = _hexDigits[(*e) & 0xF];
		*(--s) = _hexDigits[(*e) >> 4];
	}
	return hex + blen * 2;
}