ForceBru
ForceBru

Reputation: 44886

Passing string to function which accepts pointer to char

I've been working with OpenSSL library in C for a long time, but now I need to migrate to C++. OpenSSL's docs describe MD5 function like this.

unsigned char *MD5(const unsigned char *d, unsigned long n,
              unsigned char *md);

I want to pass variable of type string to that function, but it accepts only char *. Is it possible to pass string to parameter of type char * directly in C++? (I don't want to use extra manipulation with variable of type string)

Upvotes: 0

Views: 1184

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69912

just a little note, which may save you a headache later on. MD5 takes an unsigned char pointer as a parameter. This is a clue that it's actually not a string, but a pointer to bytes.

In your program if you start storing byte vectors in a std::string, you're eventually going to initialise a string with a byte vector containing a zero, which opens the possibility of a bug that's difficult to detect down the line.

It is safer to store all your byte vectors in a std::vector<unsigned char> (or std::vector<uint8_t> because this forces safe initialisation.

std::vector<unsigned char> plaintext;
// initialise plaintext here
std::vector<unsigned char> my_hash(16);
MD5(plaintext.data(), plaintext.size(), &my_hash[0]);

Upvotes: 2

legends2k
legends2k

Reputation: 32994

You could use the c_str member function that std::string sports. Example

std::string data;
// load data somehow
unsigned char md[16] = { };
unsigned char *ret = MD5(reinterpret_cast<const unsigned char*>(data.c_str()),
                         data.size(),
                         md);

If you want to do away with the ugly cast operator, define a string class that holds unsigned chars instead of chars and use that.

typedef std::basic_string<unsigned char> ustring;
ustring data;
unsigned char *ret = MD5(data.c_str(), data.size(), md);

Upvotes: 2

Related Questions