OpenSSL's EVP_DigestSignFinal() creates invalid signatures

Viewed 146

I wrote the following code that should return a signature of the provided std::string signed using an EC private key.

std::string msg = "test";
size_t messageLength = msg.length();

size_t encMessageLength;
unsigned char* encMessage;
signMessage(msg, evp_private_key, messageLength, &encMessageLength, &encMessage);

bool signMessage(std::string msg, EVP_PKEY *&key, size_t messageLength, size_t *encMessageLength, unsigned char** encMessage) {

    unsigned char * u_msg = (unsigned char*) msg.c_str();
    EVP_MD_CTX* signCtx = EVP_MD_CTX_new();


    if (EVP_DigestSignInit(signCtx,NULL, EVP_sha256(), NULL, key) <= 0) {
        return NULL;
    }

    if (EVP_DigestSignUpdate(signCtx, u_msg, messageLength) <= 0) {
        return NULL;
    }

    if (EVP_DigestSignFinal(signCtx, NULL, encMessageLength) <= 0) {
        return NULL;
    }
    *encMessage = (unsigned char*)malloc(*encMessageLength);

    if (EVP_DigestSignFinal(signCtx, *encMessage, encMessageLength) <= 0) {
        return NULL;
    }

    EVP_MD_CTX_free(signCtx);

    return true;

}

*encMessage is freed after the function call.

The length of encMessage varies greatly between 3 and 139. An example output casted and printed as char* as well as hex looks like this:

�D�b���w�x�VS:������dƀ7�@����v�B%M�X2�ky���!�h�};J>�!���h�ħ�n����/�j�U���aL����z�X���>�2�>

Length: 138
hex: 30818702414fa9b7d8cac465525add0451784bc751544702edd0e24bdb0dca44f362fc80a11b3777e78316788e56533a91c0a1eb058bf1a564c68037900640cc13b9aca776c4024201254dd55832a16b799ad2f021f468a07d3b4a3e801321bba284688fc4a7c0156e86da1e84952f8c6ab755da1dd3ec614cec10bea1bc7aac58affa9c3efb32990f3e

Another function call:

msg: 0��B

Length: 5
hex: 3081880242

What am I doing wrong?

0 Answers
Related