News for hackers. Stuff that matters.
Re:Why C++ is back by AnthonyMouse on Monday December 03, 2012 @02:24AM (#4864345)
>Why would you prefer a C++ implementation of a crypto library to a C one?

Here's an example from the EVP_Digest* man page from OpenSSL, with some comments added:

EVP_MD_CTX *mdctx;

// forget this part and get undefined behavior (but maybe it seems to work, sometimes)

mdctx = EVP_MD_CTX_create();

// forget this part? more and different runtime errors

EVP_DigestInit_ex(mdctx, md, NULL);

EVP_DigestUpdate(mdctx, mess1, strlen(mess1));

EVP_DigestUpdate(mdctx, mess2, strlen(mess2));

// md_value allocated with malloc()? don't forget to free()

EVP_DigestFinal_ex(mdctx, md_value, &md_len);

// forget this part, or remember it but miss an "if(err) return -1" statement somewhere? memory leak

EVP_MD_CTX_destroy(mdctx);

Comparable C++ implementation:

// RAII, compile error if you don't provide constructor argument instead of runtime error if you don't call init function

EVP_Digest_CTX ctx(md);

ctx.update(msg1, msg1_size);

ctx.update(msg2, msg2_size);

// return simple object: typed dynamic byte array + size with its own destructor, both digest and ctx destructors get called when function returns from anywhere

EVP_Digest digest = ctx.final_result();

And it's 4 lines of code instead of 7.

Can you explain why I would want the C version?

There are no comments on this comment yet.