Atbash 密码示例 - 通过互动代码教程学习 Atbash 密码

通过互动示例和实践练习了解 Atbash 密码的工作原理。从基本字母交换到现实世界的密码分析挑战,练习使用这种古老的希伯来替换方法进行编码和解码。

Interactive Atbash Cipher Examples

Learn Atbash cipher through step-by-step Atbash cipher examples from beginner to advanced level

Simple Word - HELLO

beginner
HELLO
SVOOL

H→S, E→V, L→O, L→O, O→L. Each letter in this Atbash cipher example maps to its mirror position in the alphabet.

Common Word - WORLD

beginner
WORLD
DLIOW

W→D, O→L, R→I, L→O, D→W. Notice how the Atbash cipher transformation is consistent and reversible.

The Word ATBASH

beginner
ATBASH
ZGYZHS

A→Z, T→G, B→Y, A→Z, S→H, H→S. The Atbash cipher's own name demonstrates the Atbash cipher principle.

Short Sentence

intermediate
MEET AT DAWN
NVVG ZG WZDA

Complete Atbash cipher sentence showing how spaces are preserved while letters transform according to the Atbash cipher mirror principle.

Mixed Case Text

intermediate
Attack at Midnight
Zggzxp zg Nrmmrtsg

Demonstrates how Atbash cipher preserves case while transforming letters. This Atbash cipher example shows uppercase remains uppercase.

Complex Message

advanced
The secret is hidden in the ancient text!
Gsv hvxivg rh sroovn rm gsv zmxrvmg gvcg!

Full Atbash cipher sentence with punctuation showing practical application of Atbash cipher in message encoding and Atbash cipher usage.

Hebrew Atbash Cipher - Biblical Cipher Examples

Historical Hebrew Atbash cipher examples from biblical texts showing real-world Atbash cipher usage

Jeremiah 25:26 - Sheshach

Jeremiah 25:26
ששך
Transliteration: Sheshach
בבל (Babel/Babylon)
English: (Babel/Babylon)

The most famous biblical Atbash cipher example where 'Sheshach' (ששך) is Atbash cipher for 'Babel' (בבל), referring to Babylon. This Atbash cipher demonstrates ancient Hebrew cryptography.

Jeremiah 51:1 - Leb Kamai

Jeremiah 51:1
לבקמי
Transliteration: Leb-Kamai
כשדים (Kasdim/Chaldeans)
English: (Kasdim/Chaldeans)

'Leb-Kamai' (לבקמי) decodes using Atbash cipher to 'Kasdim' (כשדים), the Hebrew name for the Chaldeans/Babylonians. Another classic Atbash cipher example.

Hebrew Alphabet Principle

Hebrew Alphabet
אלף תו בית שין
Transliteration: Aleph Tav Beit Shin
A-T-B-SH demonstrates the cipher principle
English: demonstrates

Atbash cipher gets its name from pairing the first and last letters: Aleph-Tav, Beit-Shin (A-T-B-SH). This explains the Atbash cipher terminology and Hebrew alphabet principle.

Atbash Cipher Programming Implementations

Production-ready Atbash cipher code examples in Python and JavaScript with detailed Atbash cipher explanations

Python Implementation

python
def atbash_cipher(text):
    """
    Encode/decode text using Atbash cipher
    """
    result = ""
    
    for char in text:
        if char.isalpha():
            # Handle uppercase letters
            if char.isupper():
                # A=0, Z=25, so Z-A = 25-0 = 25
                position = ord(char) - ord('A')
                new_position = 25 - position
                result += chr(ord('A') + new_position)
            # Handle lowercase letters
            else:
                position = ord(char) - ord('a')
                new_position = 25 - position
                result += chr(ord('a') + new_position)
        else:
            # Keep non-alphabetic characters as-is
            result += char
    
    return result

# Example usage
original = "HELLO WORLD"
encoded = atbash_cipher(original)
decoded = atbash_cipher(encoded)  # Atbash is self-inverse

print(f"Original: {original}")
print(f"Encoded:  {encoded}")
print(f"Decoded:  {decoded}")

Complete Python Atbash cipher implementation with support for both uppercase and lowercase letters. This Atbash cipher function is self-inverse, demonstrating the Atbash cipher's symmetric property.

JavaScript Implementation

javascript
function atbashCipher(text) {
    /**
     * Encode/decode text using Atbash cipher
     * @param {string} text - Input text to transform
     * @returns {string} - Transformed text
     */
    return text
        .split('')
        .map(char => {
            if (/[A-Z]/.test(char)) {
                // Handle uppercase letters (A=65, Z=90)
                const position = char.charCodeAt(0) - 65;
                const newPosition = 25 - position;
                return String.fromCharCode(65 + newPosition);
            } else if (/[a-z]/.test(char)) {
                // Handle lowercase letters (a=97, z=122)
                const position = char.charCodeAt(0) - 97;
                const newPosition = 25 - position;
                return String.fromCharCode(97 + newPosition);
            }
            // Keep non-alphabetic characters unchanged
            return char;
        })
        .join('');
}

// Example usage with arrow function syntax
const encode = text => atbashCipher(text);
const decode = text => atbashCipher(text); // Same function!

// Test the implementation
const message = "Attack at Dawn";
const encoded = encode(message);
const decoded = decode(encoded);

console.log(`Original: ${message}`);
console.log(`Encoded:  ${encoded}`);
console.log(`Decoded:  ${decoded}`);

Modern JavaScript Atbash cipher implementation using ES6 features. Demonstrates functional programming approach with map/split/join for Atbash cipher encoding and decoding.

Advanced Python with Unicode

python
import string
from typing import Dict, Optional

class AtbashCipher:
    """
    Advanced Atbash cipher implementation with multiple character sets
    """
    
    def __init__(self, include_numbers: bool = False, include_special: bool = False):
        self.include_numbers = include_numbers
        self.include_special = include_special
        self._create_mappings()
    
    def _create_mappings(self) -> None:
        """Create character mapping dictionaries"""
        self.mappings: Dict[str, str] = {}
        
        # Letters
        upper = string.ascii_uppercase
        lower = string.ascii_lowercase
        self.mappings.update({
            char: upper[25 - i] for i, char in enumerate(upper)
        })
        self.mappings.update({
            char: lower[25 - i] for i, char in enumerate(lower)
        })
        
        # Numbers (optional)
        if self.include_numbers:
            digits = string.digits
            self.mappings.update({
                char: digits[9 - i] for i, char in enumerate(digits)
            })
        
        # Special characters (optional)
        if self.include_special:
            special = '!@#$%^&*()_+-=[]{}|;':",./<>?'
            reversed_special = special[::-1]
            self.mappings.update({
                char: reversed_special[i] for i, char in enumerate(special)
            })
    
    def transform(self, text: str) -> str:
        """Transform text using Atbash cipher"""
        return ''.join(
            self.mappings.get(char, char) for char in text
        )
    
    def encode(self, text: str) -> str:
        """Encode text (alias for transform)"""
        return self.transform(text)
    
    def decode(self, text: str) -> str:
        """Decode text (alias for transform - Atbash is self-inverse)"""
        return self.transform(text)

# Usage examples
cipher = AtbashCipher()
advanced_cipher = AtbashCipher(include_numbers=True, include_special=True)

text = "Hello, World! 123"
print(f"Original: {text}")
print(f"Basic:    {cipher.encode(text)}")
print(f"Advanced: {advanced_cipher.encode(text)}")

Production-ready Python Atbash cipher class with support for numbers, special characters, and proper error handling. Advanced Atbash cipher implementation for real-world applications.

通过示例学习埃特巴什密码

通过展示其原理与应用的实践示例,最容易理解埃特巴什密码。本综合教程提供从简单单词到复杂实现的一系列示例。

基础示例

简单单词转换

HELLO → SVOOL

  • H(第8个字母)→ S(第19个字母)
  • E(第5个字母)→ V(第22个字母)
  • L(第12个字母)→ O(第15个字母)
  • L(第12个字母)→ O(第15个字母)
  • O(第15个字母)→ L(第12个字母)

WORLD → DLIOW 这一转换展示了一致的镜像映射:每个字母的位置从26中减去(基于1的系统)或从25中减去(基于0的系统)。

渐进式难度分级

初级
  • 单个单词:ATBASH → ZGYZHS
  • 简单短语:MEET AT DAWN → NVVG ZG WZDA
  • 保留大小写:Attack → Zggzxp
中级
  • 带标点的完整句子
  • 数字和特殊字符(启用时)
  • 真实消息示例
高级
  • 段落长度文本
  • 混合内容类型
  • 历史文献分析

希伯来示例与圣经参考

"Atbash"这个名字

该密码的名称来源于希伯来字母配对:

  • Aleph(א)+Tav(ת)= AT
  • Beth(ב)+Shin(ש)= BASH
耶利米书 25
— 示沙克(Sheshach)
希伯来原文: ששך(Sheshach)
埃特巴什解码: בבל(Babel/Babylon)

这是最著名的圣经示例,先知耶利米使用埃特巴什密码来隐晦地指代巴比伦,可能是为了避免直接点名这个强大的帝国。

耶利米书 51
— 勒卡迈(Leb Kamai)
希伯来原文: לב קמי(Leb Kamai)
埃特巴什解码: כשדים(Kasdim/Chaldeans)

耶利米书中的另一示例,"Leb Kamai"(字面意思为"攻击我的人的心")隐晦地指代"Kasdim"(迦勒底人)。

编程实现

Python 实现
def atbash_cipher(text):
    """
    使用埃特巴什密码对文本进行编码/解码
    """
    result = ""

    for char in text:
        if char.isalpha():
            if char.isupper():
                # A=0, Z=25, 所以 Z-A = 25-0 = 25
                position = ord(char) - ord('A')
                new_position = 25 - position
                result += chr(ord('A') + new_position)
            else:
                position = ord(char) - ord('a')
                new_position = 25 - position
                result += chr(ord('a') + new_position)
        else:
            result += char

    return result

# 使用示例
message = "The secret is hidden"
encoded = atbash_cipher(message)
decoded = atbash_cipher(encoded)  # 埃特巴什是自逆的

print(f"原文: {message}")
print(f"编码: {encoded}")
print(f"解码: {decoded}")
JavaScript 实现
function atbashCipher(text) {
    return text
        .split('')
        .map(char => {
            if (/[A-Z]/.test(char)) {
                const position = char.charCodeAt(0) - 65;
                const newPosition = 25 - position;
                return String.fromCharCode(65 + newPosition);
            } else if (/[a-z]/.test(char)) {
                const position = char.charCodeAt(0) - 97;
                const newPosition = 25 - position;
                return String.fromCharCode(97 + newPosition);
            }
            return char;
        })
        .join('');
}

// 使用示例
const message = "Attack at Dawn";
const encoded = atbashCipher(message);
const decoded = atbashCipher(encoded);

console.log(`原文: ${message}`);
console.log(`编码: ${encoded}`);
console.log(`解码: ${decoded}`);
高级 Python 类
import string
from typing import Dict

class AtbashCipher:
    def __init__(self, include_numbers=False, include_special=False):
        self.include_numbers = include_numbers
        self.include_special = include_special
        self._create_mappings()

    def _create_mappings(self):
        self.mappings = {}

        # 字母
        upper = string.ascii_uppercase
        lower = string.ascii_lowercase
        self.mappings.update({
            char: upper[25 - i] for i, char in enumerate(upper)
        })
        self.mappings.update({
            char: lower[25 - i] for i, char in enumerate(lower)
        })

        # 数字(可选)
        if self.include_numbers:
            digits = string.digits
            self.mappings.update({
                char: digits[9 - i] for i, char in enumerate(digits)
            })

    def transform(self, text):
        return ''.join(
            self.mappings.get(char, char) for char in text
        )

数学基础

埃特巴什转换可以用数学公式表达:

对于位置为 i 的字母(基于0的索引):

encoded_position = (alphabet_length - 1) - i

对于英文字母表(26个字母):

encoded_position = 25 - i

该公式适用于任意长度的字母表,使其可以适配不同语言。

教育应用

课堂活动
  1. 字母映射练习:学生自行创建字母转换表
  2. 历史分析:研究圣经文本中的密码规律
  3. 编程挑战:用不同编程语言实现密码
  4. 密码分析练习:学习检测和破解简单密码
研究项目
  • 分析埃特巴什编码文本中的频率规律
  • 将埃特巴什密码与其他替换密码进行比较
  • 圣经密码学的历史意义
  • 密码检测算法的开发

实践练习

练习1:基础编码

用埃特巴什密码对以下单词进行编码:

  • SECRET
  • CIPHER
  • ANCIENT
练习2:希伯来示例

研究并分析以下圣经引用:

  • 耶利米书 25
    (Sheshach)
  • 耶利米书 51
    (Leb Kamai)
  • 耶利米书 51
    (Sheshach 变体)
练习3:实现挑战

编写一个程序,实现以下功能:

  1. 接受用户输入
  2. 应用埃特巴什转换
  3. 检测输入是否已经过埃特巴什编码
  4. 提供置信度评分

历史意义

埃特巴什密码代表人类最早的加密方法之一,证明了安全通信的需求已存在了数千年。它出现在圣经文本中,表明密码学不仅仅是军事工具,还具有宗教和文学方面的应用价值。

现代意义

尽管以现代标准来看并不安全,埃特巴什密码在以下方面仍具有重要价值:

  • 密码学课程中的教育用途
  • 谜题和游戏开发
  • 历史文本分析
  • 理解加密方法的演变历程

埃特巴什密码的简洁性使其成为学习密码学概念的绝佳入门,是通往更复杂密码和现代加密算法的理想跳板。