0

So i have this function which receives a pointer:

int myfunc( const char *token, unsigned char *plaintext )

I do my stuff and i end up with a char array:

unsigned char my_plaintext[1024];

Now i need to set that pointer (plaintext) to what's in my_plaintext. I've tried many different ways but i haven't yet figure this one out...

This part is in a cpp file, and i've even tried:

std::string tmpstr( my_plaintext );

But this comes back with:

token_crypto.cpp:131:13: error: invalid conversion from 'char*' to 'unsigned char*' [-fpermissive]
         my_plaintext
         ^~~~~~~~~~~~

And

std::string tmpstr( (char *)my_plaintext );

'�5�B'

this does compiles but the content is all wrong:

EDIT:

The content of my_plaintext is fine:

int myfunc( const char *token, unsigned char *plaintext ) {
    unsigned char my_plaintext[1024];
    ... some processing stuff (specifically gcm_decrypt) to which is pass my_plaintext ...

    cout << my_plaintext

    // prints: hello:world

but then however i try set the contents of plaintext to whatever is in my_plaintext either fails at compilation or prints some weird characters.

David Villasmil
  • 395
  • 2
  • 19
  • I think your final "content is all wrong" problem is that you have string data in some encoding, and you're printing it out using some other encoding. Can you provide a minimal example that shows what you're doing, perhaps hard-coding the C string you have from your "myfunc"? – Paul Hankin Jun 15 '20 at 14:35
  • Thanks Paul. But no, the data contained in my_plaintext is an alphanumeric string of characters :( – David Villasmil Jun 15 '20 at 14:36
  • Will do what you suggest. – David Villasmil Jun 15 '20 at 14:36
  • If you need `std::string` operations and memory management with `unsigned char` you could use `std::basic_string`. – joshwilsonvu Jun 15 '20 at 14:42

2 Answers2

0

If you know that plaintext already points at an array that is 1024 long (or longer) then you can use memmove():

int myfunc( const char *token, unsigned char *plaintext )
{
    unsigned char my_plaintext[1024];
    /* ... fill in my_plaintext here ... */
    memmove(plaintext, my_plaintext, 1024);
    /* ... rest of function ... */
}

Note that the parameters to memmove are destintation and then source rather than the other way round.

It's up to the caller of your function to make sure the pointer they pass in points to at least 1024 bytes.

You can use memcpy() instead in this case, but using memmove() is good practice in general.

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
-1

The C++ string constructor doesn't take an unsigned char *. See the C++ reference here:

http://www.cplusplus.com/reference/string/string/string/

You need to cast the unsigned char array to a char array. See how to do that here:

How to Convert unsigned char* to std::string in C++?

bstache
  • 11
  • 2