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

XOR Cipher (XOR Encryption) ใน C++

XOR Cipher คืออะไร?

XOR Cipher (หรือ XOR Encryption) เป็นวิธีเข้ารหัสข้อมูลแบบ Symmetric-key algorithm ใช้ operation XOR (^) ระหว่างข้อมูลต้นทาง (plaintext) และคีย์ (key)

คุณสมบัติสำคัญ

  • Symmetric: เข้ารหัสและถอดรหัสใช้ operation เดียวกัน (XOR)
  • Self-inverse: (P ^ K) ^ K = P
  • Fast: XOR เป็น CPU instruction ระดับฮาร์ดแวร์ เร็วมาก
  • Simple: เข้าใจและ implement ได้ง่าย

ข้อจำกัด (สำคัญมาก)

XOR Cipher ด้วยคีย์ตัวเดียว (single-byte key) ไม่ปลอดภัยต่อการโจมตีแบบ Known-plaintext, Frequency analysis, หรือ Brute-force

ในทางปฏิบัติ ต้องใช้:

  • Key ที่ยาวเท่าข้อมูล (One-time pad - ทฤษฎีแล้ว unbreakable)
  • Stream cipher ที่สร้าง keystream จาก key สั้น (เช่น ChaCha20, AES-CTR)
  • Block cipher modes (AES-GCM, ChaCha20-Poly1305)

ตัวอย่างการใช้งาน (Educational Purpose Only)

#include <iostream>
#include <cstring>
using namespace std;

void xorCipher(char* data, size_t len, char key) {
    for (size_t i = 0; i < len; i++) {
        data[i] ^= key;
    }
}

void xorCipherString(string& str, char key) {
    for (char& c : str) {
        c ^= key;
    }
}

int main() {
    string original = "Hello, World!";
    char key = 'K';  // Single-byte key (INSECURE)
    
    cout << "Original: " << original << endl;
    
    // Encrypt
    xorCipherString(original, key);
    cout << "Encrypted: ";
    for (unsigned char c : original) cout << hex << (int)c << ' ';
    cout << dec << endl;
    
    // Decrypt (same operation)
    xorCipherString(original, key);
    cout << "Decrypted: " << original << endl;
    
    return 0;
}

ผลลัพธ์

Original: Hello, World!
Encrypted: 3 2e 27 27 24 6b 3b 24 3d 27 2f 6b
Decrypted: Hello, World!

Multi-byte Key Version (Vigenère-style)

void xorCipherMultiByte(string& data, const string& key) {
    for (size_t i = 0; i < data.size(); i++) {
        data[i] ^= key[i % key.size()];
    }
}

Modern C++ Implementation

#include <algorithm>
#include <string>
#include <vector>

string xorEncrypt(const string& plaintext, const string& key) {
    string ciphertext(plaintext.size(), '\0');
    transform(plaintext.begin(), plaintext.end(), key.begin(), 
              ciphertext.begin(), 
              [&key, i = 0](char p, char k) mutable { 
                  return p ^ key[i++ % key.size()]; 
              });
    return ciphertext;
}

คำเตือนด้านความปลอดภัย

⚠️ WARNING: โค้ดในบทความนี้เป็นเพื่อ การศึกษาเท่านั้น ไม่ควรใช้ XOR cipher แบบง่ายนี้ใน production จริง สำหรับการเข้ารหัสจริง ให้ใช้ library มาตรฐานเช่น:
  • OpenSSL (AES, ChaCha20)
  • libsodium (XChaCha20-Poly1305)
  • C++23 <cipher> (upcoming)

สรุป

XOR Cipher เป็นหลักการพื้นฐานของ symmetric encryption เรียนรู้เพื่อเข้าใจ cryptography basics แต่ในการใช้งานจริง ต้องใช้ алгоритม และ library ที่ผ่านการ audit และมาตรฐานอุตสาหกรรมแล้ว