I have a 96 bytes long ecdsa signature created with sha384 algorithm by a smart card in raw format.It is composed of two 48 bytes long integers r and s. The ecdsa signature is in a buffer pointed to by sign_ptr. I'm converting the raw format signature into buf_out in ASN1 format with this function (in C):
int convert_ecdsa_sha384_sign(char **buf_out, char *sign_ptr)
{
buf_out[0]=0x30; /* Type = Sequence of */
buf_out[2]=0x02; /* Type = Integer */
/* Verify if negative bit is set */
if (!(sign_ptr[0] & 0x80))
{
buf_out[3]=0x30; /* Length */
memcpy(&(buf_out[4]), sign_ptr, 48); /* Copy first integer */
}
else
{
/* Negative bit is set. Add one padding byte */
buf_out[3]=0x31; /* Length */
buf_out[4]=0x00; /* Padding */
memcpy(&(buf_out[5]), sign_ptr, 48); /* Copy first integer */
sign_offset += 1;
}
buf_out[52+sign_offset]=0x02; /* Type = Integer */
/* Verify if negative bit is set */
if (!(sign_ptr[48] & 0x80))
{
buf_out[53+sign_offset]=0x30; /* Length */
memcpy(((&(buf_out[54]))+ sign_offset), sign_ptr + 48, 48); /* Copy second integer */
}
else
{
/* Negative bit is set. Add one padding byte */
buf_out[53+sign_offset]=0x31; /* Length */
buf_out[54+sign_offset]=0x00; /* Padding */
memcpy(((&(buf_out[55]))+ sign_offset), sign_ptr + 48, 48); /* Copy second integer */
sign_offset += 1;
}
buf_out[1]= 100 + sign_offset; /* Total signature length */
return 1;
}
I am wondering if there is an equivalent openssl function that can help me to do this in a more elegant way? I did look at many d2i functions (d2i_ASN1_xxxx, ASN1_item_d2i, ASN_d2i_func, etc.) but it is not clear which one suits.
Here is the answer I got from Dr Stephen N. Henson. OpenSSL project core developer in openssl-users forum:
"The structure ECDSA_SIG is the one you need.
In outline: allocate the structure using ECDSA_SIG_new, set the r and s values using BN_bin2bn, encode the result with i2d_ECDSA_SIG and finally free with ECDSA_SIG_free".