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

เข้ารหัสสตริงด้วย Caesar Cipher ใน JavaScript

Caesar Cipher คืออะไร

Caesar Cipher เป็นเทคนิคเข้ารหัสแบบแทนที่ (Substitution Cipher) ที่ง่ายที่สุด เลื่อนตัวอักษรในอัลฟาเบทไปข้างหน้าหรือข้างหลังจำนวนคงที่

ตัวอย่าง

Shift 3 ตัวไปขวา: A→D, B→E, C→F... Z→C

Shift -3 (ซ้าย): D→A, E→B, F→C... C→Z

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

const str = 'thisIsAString';

const getMap = (legend, shift) => {
  return legend.reduce((charsMap, currentChar, charIndex) => {
    const copy = { ...charsMap };
    let ind = (charIndex + shift) % legend.length;
    if (ind < 0) ind += legend.length;
    copy[currentChar] = legend[ind];
    return copy;
  }, {});
};

const encrypt = (str, shift = 0) => {
  const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
  const map = getMap(legend, shift);
  return str
    .toLowerCase()
    .split('')
    .map(char => map[char] || char) // เก็บตัวอักษรไม่ใช่ a-z ไว้
    .join('');
};

console.log(encrypt(str, 6)); // znoyoygyzxotm

ผลลัพธ์

znoyoygyzxotm

โค้ดเวอร์ชันปรับปรุง (รองรับใหญ่-เล็ก, โมดูลาร์)

const caesarCipher = (str, shift) => {
  const normalizeShift = shift % 26;
  
  return str.split('').map(char => {
    const code = char.charCodeAt(0);
    
    // Uppercase A-Z (65-90)
    if (code >= 65 && code <= 90) {
      return String.fromCharCode((code - 65 + normalizeShift + 26) % 26 + 65);
    }
    // Lowercase a-z (97-122)
    if (code >= 97 && code <= 122) {
      return String.fromCharCode((code - 97 + normalizeShift + 26) % 26 + 97);
    }
    return char; // Non-alphabetic
  }).join('');
};

const caesarDecrypt = (str, shift) => caesarCipher(str, -shift);

// ทดสอบ
const original = 'Hello, World!';
const encrypted = caesarCipher(original, 3); // Khoor, Zruog!
const decrypted = caesarDecrypt(encrypted, 3); // Hello, World!

console.log({ original, encrypted, decrypted });

การแฮก Caesar Cipher (Frequency Analysis)

const crackCaesar = (ciphertext) => {
  const freq = 'etaoinshrdlcumwfgypbvkjxqz'; // English frequency
  const results = [];
  
  for (let shift = 0; shift < 26; shift++) {
    const decrypted = caesarDecrypt(ciphertext, shift);
    // Scoring based on letter frequency
    let score = 0;
    for (let char of decrypted.toLowerCase()) {
      const idx = freq.indexOf(char);
      if (idx !== -1) score += 26 - idx;
    }
    results.push({ shift, text: decrypted, score });
  }
  
  return results.sort((a, b) => b.score - a.score);
};

ข้อจำกัด

  • ไม่ปลอดภัย - แฮกได้ง่ายด้วย Brute Force (แค่ 25 ครั้ง) หรือ Frequency Analysis
  • ใช้ได้เฉพาะอัลฟาเบทอังกฤษ
  • เหมาะสำหรับการเรียนรู้/ออบฟัสเคชันเบาๆ เท่านั้น