Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ซ่อนสตริงใน Binary Code ด้วย C++

แปลงสตริงเป็น hexadecimal representation เพื่อ "ซ่อน" ข้อความใน binary (obfuscation เบื้องต้น)

วิธีทำ

  1. อ่านแต่ละ character ของ string
  2. ดึงค่า ASCII (integer)
  3. แปลงเป็น hexadecimal ด้วย stringstream + std::hex

โค้ดตัวอย่าง

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

string dec_to_hex(int decimal) {
    stringstream ss;
    ss << hex << decimal;
    return ss.str();
}

int main() {
    string str = "This is a sample text";
    for (char c : str) {
        cout << dec_to_hex(static_cast<int>(c)) << ' ';
    }
}

ผลลัพธ์

54 68 69 73 20 69 73 20 61 20 73 61 6d 70 6c 65 20 74 65 78 74

ค่าที่ได้คือ ASCII hex: T=0x54, h=0x68, i=0x69, s=0x73, space=0x20, ...

ข้อจำกัด

  • ไม่ใช่ encryption จริง แค่ encoding ง่าย ใครก็ decode ได้
  • สำหรับความปลอดภัยจริง ใช้ cryptography libraries (OpenSSL, libsodium, C++23 <crypt> proposal)
  • String literals ใน binary ยังอ่านได้ด้วย strings command