Search code examples
c++stringencryptionbytecrypto++

How to cast a char* to a byte* in c++?


I am very new in c++ and want to cast a char* from a std::string to a byte*.

Here is my code:

inline string XOR(const string &value, const string &key) {
  string retval(value);
  CryptoPP::xorbuf(&retval[0], &key[0], retval.length());
  return retval;
}

In g++, the output is:

AESXCBC128.cpp: In function ‘std::string CryptoPP::XOR(const string&, const string&)’:
AESXCBC128.cpp:79:48: error: invalid conversion from ‘char*’ to ‘byte* {aka unsigned char*}’ [-fpermissive]
     xorbuf(&retval[0], &key[0], retval.length());
                                                ^
AESXCBC128.cpp:45:6: error:   initializing argument 1 of ‘void CryptoPP::xorbuf(byte*, const byte*, size_t)’ [-fpermissive]
 void xorbuf(byte *buf, const byte *mask, size_t count)
      ^
AESXCBC128.cpp:79:48: error: invalid conversion from ‘const char*’ to ‘const byte* {aka const unsigned char*}’ [-fpermissive]
     xorbuf(&retval[0], &key[0], retval.length());
                                                ^
AESXCBC128.cpp:45:6: error:   initializing argument 2 of ‘void CryptoPP::xorbuf(byte*, const byte*, size_t)’ [-fpermissive]
 void xorbuf(byte *buf, const byte *mask, size_t count)

Solution

  • inline string XOR(const string &value, const string &key) {
      string retval(value);
      CryptoPP::xorbuf(&retval[0], &key[0], retval.length());
      return retval;
    }
    

    Crypto++ typedefs a byte in confg.h:

    typedef unsigned char byte;
    

    You can use something like:

    CryptoPP::xorbuf(
        reinterpret_cast<byte*>(&retval[0]),
        reinterpret_cast<const byte*>(&key[0]),
        retval.length());
    

    Or, you can do it with C-style casts:

    CryptoPP::xorbuf((byte*)&retval[0], (const byte*)&key[0], retval.length());
    

    Here are some similar questions for SecByteBlock, which is a byte array rather than a char array:

    Here are some references on C++ casting: