1

First off, I've Googled this question over the past few days but everything I find doesn't work. I don't receive runtime errors but when I type in the same key (in the form of a hex string) that the program generates to encrypt, decryption fails (but using the generated key throughout the program works fine). I'm trying to enter a hex string (format: 00:00:00...) and turn it into a 32-byte byte array. The input comes from getpass(). I've done this before in Java and C# but I'm new to C++ and everything seems much more complicated. Any help would be greatly appreciated :) Also I'm programming this on a linux platform so I'd like to avoid Windows-only functions.

Here is an example of what 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];
4

2 回答 2

1

如果您的输入格式为:AA:BB:CC,您可以编写如下内容:

#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;
}
于 2013-05-20T04:26:36.193 回答
-1

这个怎么样?

把它当成一个词来读,然后对它进行操作?您可以在 convert() 中进行任何大小检查格式检查。

#include <iostream>
#include <string>
#include <vector>

char convert(char c)
{
    using namespace std;
    // do whatever decryption stuff you want here
    return c;
}

void test()
{
    using namespace std;

    string word;
    cin >> word;

    vector<char> password;

    for (int i = 0; i < word.length(); i++)
    {
        password.push_back(convert(word[i]));
    }

    for (int i = 0; i < password.size(); i++)
    {
        cout << password[i];
    }

    cout << "";
}

int main()
{
    using namespace std;
    char wait = ' ';

    test();

    cin >> wait;
}

在这里不使用 cin 是否有具体原因?

于 2013-05-20T04:26:39.933 回答