繁体   English   中英

C ++十六进制字符串到字节数组

[英]C++ Hex string to byte array

首先,过去几天我在Google上搜索了此问题,但我发现的所有内容均无效。 我没有收到运行时错误,但是当我键入程序生成的用于加密的相同密钥(以十六进制字符串的形式)时,解密失败(但是在整个程序中使用生成的密钥可以正常工作)。 我正在尝试输入一个十六进制字符串(格式:00:00:00 ...)并将其转换为32字节的字节数组。 输入来自getpass() 我以前在Java和C#中已经做到了,但是我是C ++的新手,一切似乎都更加复杂。 任何帮助将不胜感激:)另外,我正在linux平台上对此进行编程,因此我想避免使用仅Windows功能。

这是我尝试过的一个示例:

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];

如果您输入的格式为: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;
}

这个怎么样?

作为一个单词阅读并在之后对其进行操作? 您可以在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的特定原因吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM