-1

I have a string of hex values separated by white spaces.

std::string hexString = "0x60 0xC7 0x80" and so on...

I need to read this and store in the unsigned char array:

unsigned char array[] = {0x60, 0xC7, 0x80}.

I am stuck with this. Could someone please help?

Scenario:

I am writing AES 256 CBC encryption/decryption program. The encryption and decryption pieces are isolated. We are planning to encrypt DB passwords from clear text to encrypted one stored in the config files with (key, value). Standalone encryption binary will produce a hex equivalent. We encrypt all the necessary attributes separately and write them into the config file. The application at run time should do the decryption of those configs to use it for connection to DB, etc. I have to read hex string and send it as char array to the AES decryption algorithm.

sg7
  • 6,108
  • 2
  • 32
  • 40
  • 3
    The real question is why you ended up with a hex string in the first place – David Heffernan Oct 16 '14 at 18:32
  • You seem to be using C++, but you do know that C is a different language, and more modern C won't compile as C++? – crashmstr Oct 16 '14 at 18:34
  • @crashmstr Genuinely curious: which recent changes make C less compatible with C++? – Peter - Reinstate Monica Oct 16 '14 at 20:16
  • @PeterSchneider I should say more correctly "may not" as well as the fact that the "natural" way to do something will probably not be the same. But VLAs are an "old" feature of C back in C99. It is supported as an extension by some C++ compilers and seems to be coming to C++14, but both languages have moved on with separate paths - [C11 (C standard revision)](http://en.wikipedia.org/wiki/C11_(C_standard_revision)) – crashmstr Oct 16 '14 at 22:54
  • Thank you .. My actual scenario is I am writing AES 256 CBC encryption/decryption program.Where encryption and decryption pieces are isolated. we are planning to encrypt DB passwords from clear text to encrypted in config files(key, value). SO, standalone encryption binary will produce a hex equivalant. So we can encrypt all necessary attribs separately and write them in to config file. But the application at run time should decrypt those configs and use to connect to db etc,so I got in to this situation of reading hex string and send it as char array to AES decrypt. – subhash kollipara Oct 18 '14 at 18:11

2 Answers2

0

Here's an example:

#include <regex>
#include <string>
#include <iostream>

template <typename Iterator>
class iterator_pair {
    public:
        iterator_pair(Iterator first, Iterator last): f_(first), l_(last) {}
        Iterator begin() const { return f_; }
        Iterator end() const { return l_; }

    private:
        Iterator f_;
        Iterator l_;
};

template <typename Iterator>
iterator_pair<Iterator> make_iterator_pair(Iterator f, Iterator l) {
    return iterator_pair<Iterator>(f, l);
}

int main() {
    std::string hexString = "0x60 0xC7 0x80";
    std::regex whitespace("\\s+");
    std::vector<int> hexArray;

    auto tokens = make_iterator_pair(
            std::sregex_token_iterator(hexString.begin(), hexString.end(), whitespace, -1),
            std::sregex_token_iterator());

    for (auto token : tokens)
        hexArray.push_back(stoi(token, 0, 0));

    for (auto hex : hexArray)
        std::cout << hex << std::endl;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

I have std::string hexString... I need to store it in unsigned char array[].

Please take a look at the following solution which is based on strtoul function. The input string to strtoul may consist of any number of blanks and/or tabs, possibly followed by a sign, followed by a string of digits. So even imperfect input like " 01 2 \t ab \t\t 3\n" can be properly parsed.

Function:

unsigned char * create_hex_array (const std::string * str, size_t * nr_of_elements);

takes pointer to the input std::string hexString creates and returns unsigned char array as well as count of elements in the array.

#include <iostream>     // std::cout, std::endl
#include <sstream>      // std::stringstream
#include <iomanip>      // std::setfill, std::setw
#include <string>       // std::string
#include <cstring>      // functions to manipulate C strings and arrays

unsigned char * create_hex_array (const std::string * str, size_t * nr_of_elements)
{
    size_t index = 0;                       // elements counter       
    size_t arr_len = str->size () / 2 + 1;  // maximum number or array elements        
    const char *current = str->c_str ();    // start from the beginning of the string   
    char *end = NULL;                       // init the end pointer 
    unsigned char *arr = new unsigned char[arr_len]; // allocate memory for our array

    while (1)
    {
        unsigned long hex = strtoul (current, &end, 16);  
        if (current == end)                 // end of string reached
            break;
        arr[index] = (unsigned char) hex;   // store the hex number in the array 
        index++;                            // increase index to the next slot in array    
        current = end;                      // move the to next number
    }

    *nr_of_elements = index;                // return number of elements in the array             
    return arr;                             // return created array 
}

void print_hex_array (size_t size, unsigned char *arr)
{
    std::cout << "Nr of elements in the array is = " << size << std::endl;
    // Fancy print out:
    // Getting a buffer into a stringstream in hex representation with zero padding
    // with 0-padding on small values so  `5` would become `05`
    std::stringstream ss;
    ss << std::hex << std::setfill ('0');

    for (size_t i = 0; i < size; i++)
    {
        // In C this is enough:  printf("%02x ", arr[i]);
        ss << std::setw (2) << static_cast < unsigned >(arr[i]) << " ";
    }

    std::cout << ss.rdbuf() << std::endl;
}

int main ()
{
    const std::string hexString = " 5 8d  77 77 96 1 \t\t bc 95 b9 ab 9d 11 \n";  
    size_t arr_size;                    // Number of elements in the array

    unsigned char * array = create_hex_array (&hexString, &arr_size); 
    print_hex_array (arr_size, array);  // printout with 0- padding.

    delete[]array;                      // release memory
    return 0;
}

Output:

Nr of elements in the array is = 12                                                                                                                    
05 8d 77 77 96 01 bc 95 b9 ab 9d 11 
sg7
  • 6,108
  • 2
  • 32
  • 40