Commit 1fadbf4b authored by filatov's avatar filatov

fix lading zeroes in PubKey generation

parent febd809b
......@@ -21,6 +21,7 @@
#define ARRAYSIZE(A) (sizeof(A)/sizeof(A[0]))
static char * _bin2hex(char * hex, int hlen, const char * bin, int blen);
typedef struct {
int nid;
const char * name;
......@@ -105,7 +106,6 @@ void * ecc_api_key_gen(ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg)
if (key){
EC_KEY_set_group(key, _curves[pk_alg]);
EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE);
if (!EC_KEY_generate_key(key)){
ERR_print_errors_fp(stderr);
fflush(stderr);
......@@ -215,22 +215,19 @@ int ecc_api_key_private_save(void* key, const char* path, ecc_format format)
const BIGNUM * ecbn;
ecbn = EC_KEY_get0_private_key(eckey);
if (ecbn){
char * buf = NULL;
int len = BN_num_bytes(ecbn);
if (format == ecc_bin){
buf = (char *)OPENSSL_malloc(len);
BN_bn2bin(ecbn, (unsigned char *)buf);
rc = 0;
}
else if (format == ecc_hex){
buf = BN_bn2hex(ecbn);
len = strlen(buf);
int bnlen = BN_num_bytes(ecbn);
int len = (bnlen < 32) ? 32 : bnlen;
char * buf = (char *)OPENSSL_malloc(len*2+1);
if (bnlen < len) memset(buf, 0, len - bnlen);
BN_bn2bin(ecbn, (unsigned char *)(buf + len - bnlen));
if (format == ecc_hex){
char * c = _bin2hex(buf, len * 2 + 1, buf, len);
*c = 0;
len = c - buf;
rc = 0;
}
if (buf){
rc = (len == fwrite(buf, 1, len, f)) ? 0 : -1;
OPENSSL_free(buf);
}
rc = (len == fwrite(buf, 1, len, f)) ? 0 : -1;
OPENSSL_free(buf);
}
}
fclose(f);
......@@ -465,3 +462,24 @@ int ecc_sign(void * key, const char * data, int length, char ** psig, int max
}
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;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment