C++ Hex string to byte array -


first off, i've googled question on past few days find doesn't work. don't receive runtime errors when type in same key (in form of hex string) program generates encrypt, decryption fails (but using generated key throughout program works fine). i'm trying enter hex string (format: 00:00:00...) , turn 32-byte byte array. input comes getpass(). i've done before in java , c# i'm new c++ , seems more complicated. appreciated :) i'm programming on linux platform i'd avoid windows-only functions.

here example of i've tried:

char *pass = getpass("key: ");  std::stringstream converter; std::istringstream ss( pass ); std::vector<byte> bytes;  std::string word; while( ss >> word ) {     byte temp;     converter << std::hex << word;     converter >> temp;     bytes.push_back( temp ); } byte* keybytes = &bytes[0]; 

if input has format: aa:bb:cc, write this:

#include <iostream> #include <sstream> #include <string> #include <vector> #include <cstdint>  struct hex_to_byte {     static uint8_t low(const char& value)     {         if(value <= '9' && '0' <= value)         {             return static_cast<uint8_t>(value - '0');         }         else // ('a' <= value && value <= 'f')         {             return static_cast<uint8_t>(10 + (value - 'a'));         }     }      static uint8_t high(const char& value)     {         return (low(value) << 4);     } };  template <typename inputiterator> std::string from_hex(inputiterator first, inputiterator last) {     std::ostringstream oss;     while(first != last)     {         char highvalue = *first++;         if(highvalue == ':')             continue;          char lowvalue = *first++;          char ch = (hex_to_byte::high(highvalue) | hex_to_byte::low(lowvalue));         oss << ch;     }      return oss.str(); }  int main() {     std::string pass = "ab:dc:ef";     std::string bin_str = from_hex(std::begin(pass), std::end(pass));     std::vector<std::uint8_t> v(std::begin(bin_str), std::end(bin_str)); // bytes: [171, 220, 239]     return 0; } 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -