簡體   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