Monday, September 26, 2005

Deep trouble with OpenSSL EVP API's

I was totally flabbergasted with a piece of code today. I was trying to calculate MD5 hash with EVP API's of OpenSSL library. The API's worked fine to calculate the hash but somehow by completely out of my knowledge it was garbling a std::string. Later I replaced the code with some C functions and computed the hash myself. It took me one hour to find the culprit code snippet and then it took me two hours to believe that it is actually the well-known OpenSSL library which is causing the mess. Here is the code I was using:

                const EVP_MD *pMd(NULL);
                unsigned char puchKey[EVP_MAX_MD_SIZE];
                unsigned int uiKeyLen(0);
                EVP_MD_CTX MDContext;
                // Check if MD5 is available

                if(NULL == (pMd = EVP_get_digestbyname("md5")))
                        LOGL(2, "Digest md5 not found");
                        return sMessageIntegrity;
                // Compute key with MD5 hash
                EVP_DigestInit(&MDContext, EVP_md5());//pMd);
                std::ostringstream ossBuffer;
                ossBuffer << p_rsUsername << ':' << p_rsRealm << ':' << p_rsPassword;
                std::string sTemp(ossBuffer.str());
                EVP_DigestUpdate(&MDContext, static_cast<const void*> (, static_cast<unsigned int> (sTemp.size()));
                EVP_DigestFinal(&MDContext, puchKey, &uiKeyLen);

It was garbling a member std::string of the class. Can someone tell me what is wrong with the code???

No comments: