关键词密码示例与代码实现

通过示例推演、交互练习和代码样例理解关键词替换字母表的构造与使用方式。

关键词密码示例

查看从基础到进阶的关键词密码示例,并包含历史风格场景。

简单关键词示例

使用关键词 ZEBRA 展示关键词密码最核心的构造和替换逻辑。

入门
ZEBRA
ZEBRACDFGHIJKLMNOPQSTUVWXY
HELLO WORLD
GJKKF VFEKX

什么是一个简单的关键词密码示例?

常见示例会使用 ZEBRA 作为关键词,生成字母表 ZEBRACKDFGHIJLMNOPQSTUVWXY,再据此对 HELLO 等词进行替换。

为什么这里提供代码示例?

代码示例能直观展示如何去重关键词、构建替换字母表,以及在处理文本时保留大小写。

练习时应该重点关注什么?

重点观察关键词如何改变字母表顺序,以及同一个字母在整段文本中始终使用同一映射。

关键词密码示例:带代码的完整编程指南

本综合指南提供关键词密码(Keyword Cipher)的实际示例和完整编程实现。无论你是在学习密码学、实现密码算法还是研究历史加密方法,这些示例都提供了与单表替换密码的实践体验。

基础示例

简单关键词变换

让我们从使用关键词"ZEBRA"的直接示例开始:

关键词:ZEBRA 标准字母表:ABCDEFGHIJKLMNOPQRSTUVWXYZ 密码字母表:ZEBRACKDFGHIJLMNOPQSTUVWXY

加密过程

  • 明文:HELLO WORLD
  • 映射:H→G,E→J,L→K,L→K,O→F
  • 密文:GJKKF VFEKX

逐步变换

  1. 去除关键词中的重复字母:ZEBRA(无重复)
  2. 追加剩余字母:ZEBRACKDFGHIJLMNOPQSTUVWXY
  3. 将每个明文字母映射到对应的密码字母
  4. 保留空格和标点
历史外交示例

关键词:MONARCHY 背景:17 世纪欧洲外交密码 明文:THE TREATY IS SIGNED 密文:TDO THIPTS YA AYGFOH

此示例展示了启蒙时代外交通信的加密方式,关键词密码为政治往来提供了足够的安全性。

编程实现

Python 实现

以下是关键词密码操作的完整 Python 类:

class KeywordCipher:
    def __init__(self, keyword):
        """Initialize the cipher with a keyword."""
        self.keyword = keyword.upper()
        self.standard_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        self.cipher_alphabet = self._generate_cipher_alphabet()
        self.encrypt_map = self._create_encrypt_map()
        self.decrypt_map = self._create_decrypt_map()

    def _generate_cipher_alphabet(self):
        """Generate cipher alphabet from keyword."""
        # Remove duplicates while preserving order
        seen = set()
        clean_keyword = ''.join(char for char in self.keyword
                               if char.isalpha() and char not in seen
                               and not seen.add(char))

        # Add remaining letters
        remaining = ''.join(char for char in self.standard_alphabet
                          if char not in clean_keyword)

        return clean_keyword + remaining

    def _create_encrypt_map(self):
        """Create encryption mapping dictionary."""
        mapping = {}
        for i, char in enumerate(self.standard_alphabet):
            mapping[char] = self.cipher_alphabet[i]
            mapping[char.lower()] = self.cipher_alphabet[i].lower()
        return mapping

    def _create_decrypt_map(self):
        """Create decryption mapping dictionary."""
        mapping = {}
        for i, char in enumerate(self.cipher_alphabet):
            mapping[char] = self.standard_alphabet[i]
            mapping[char.lower()] = self.standard_alphabet[i].lower()
        return mapping

    def encrypt(self, plaintext):
        """Encrypt plaintext using the keyword cipher."""
        return ''.join(self.encrypt_map.get(char, char) for char in plaintext)

    def decrypt(self, ciphertext):
        """Decrypt ciphertext using the keyword cipher."""
        return ''.join(self.decrypt_map.get(char, char) for char in ciphertext)

    def get_alphabet_mapping(self):
        """Return the alphabet mapping for analysis."""
        return {
            'standard': self.standard_alphabet,
            'cipher': self.cipher_alphabet,
            'keyword': self.keyword
        }

# Example usage
def main():
    # Create cipher instance
    cipher = KeywordCipher('CRYPTOGRAPHY')

    # Test messages
    messages = [
        "Hello World",
        "The quick brown fox jumps over the lazy dog",
        "ATTACK AT DAWN"
    ]

    print(f"Keyword: {cipher.keyword}")
    print(f"Cipher Alphabet: {cipher.cipher_alphabet}")
    print("-" * 50)

    for message in messages:
        encrypted = cipher.encrypt(message)
        decrypted = cipher.decrypt(encrypted)

        print(f"Original:  {message}")
        print(f"Encrypted: {encrypted}")
        print(f"Decrypted: {decrypted}")
        print(f"Match: {message == decrypted}")
        print("-" * 30)

if __name__ == "__main__":
    main()
JavaScript 实现

浏览器兼容的 JavaScript 版本,带 DOM 集成:

class KeywordCipher {
    constructor(keyword) {
        this.keyword = keyword.toUpperCase();
        this.standardAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        this.cipherAlphabet = this.generateCipherAlphabet();
        this.encryptMap = this.createEncryptMap();
        this.decryptMap = this.createDecryptMap();
    }

    generateCipherAlphabet() {
        // Remove duplicates from keyword
        const uniqueKeyword = [...new Set(this.keyword.split(''))]
            .filter(char => /[A-Z]/.test(char))
            .join('');

        // Generate remaining letters
        const remaining = this.standardAlphabet
            .split('')
            .filter(char => !uniqueKeyword.includes(char))
            .join('');

        return uniqueKeyword + remaining;
    }

    createEncryptMap() {
        const map = new Map();
        for (let i = 0; i < this.standardAlphabet.length; i++) {
            const std = this.standardAlphabet[i];
            const cipher = this.cipherAlphabet[i];
            map.set(std, cipher);
            map.set(std.toLowerCase(), cipher.toLowerCase());
        }
        return map;
    }

    createDecryptMap() {
        const map = new Map();
        for (let i = 0; i < this.standardAlphabet.length; i++) {
            const std = this.standardAlphabet[i];
            const cipher = this.cipherAlphabet[i];
            map.set(cipher, std);
            map.set(cipher.toLowerCase(), std.toLowerCase());
        }
        return map;
    }

    encrypt(plaintext) {
        return plaintext
            .split('')
            .map(char => this.encryptMap.get(char) || char)
            .join('');
    }

    decrypt(ciphertext) {
        return ciphertext
            .split('')
            .map(char => this.decryptMap.get(char) || char)
            .join('');
    }

    // Utility methods for web integration
    static createFromForm() {
        const keyword = document.getElementById('keyword').value;
        return new KeywordCipher(keyword);
    }

    encryptFromDOM() {
        const plaintext = document.getElementById('plaintext').value;
        const result = this.encrypt(plaintext);
        document.getElementById('ciphertext').value = result;
        return result;
    }

    decryptFromDOM() {
        const ciphertext = document.getElementById('ciphertext').value;
        const result = this.decrypt(ciphertext);
        document.getElementById('plaintext').value = result;
        return result;
    }
}

// Web interface integration
document.addEventListener('DOMContentLoaded', function() {
    let cipher = null;

    // Initialize cipher when keyword changes
    document.getElementById('keyword').addEventListener('input', function() {
        const keyword = this.value;
        if (keyword) {
            cipher = new KeywordCipher(keyword);
            updateAlphabetDisplay();
        }
    });

    // Encrypt button handler
    document.getElementById('encryptBtn').addEventListener('click', function() {
        if (cipher) {
            cipher.encryptFromDOM();
        }
    });

    // Decrypt button handler
    document.getElementById('decryptBtn').addEventListener('click', function() {
        if (cipher) {
            cipher.decryptFromDOM();
        }
    });

    function updateAlphabetDisplay() {
        if (cipher) {
            document.getElementById('standardAlphabet').textContent =
                cipher.standardAlphabet;
            document.getElementById('cipherAlphabet').textContent =
                cipher.cipherAlphabet;
        }
    }
});

高级示例

强度测试算法
def analyze_keyword_strength(keyword):
    """Analyze the cryptographic strength of a keyword."""
    analysis = {
        'length': len(keyword),
        'unique_letters': len(set(keyword.upper())),
        'duplicates': [],
        'strength': 'weak'
    }

    # Find duplicate letters
    seen = set()
    for char in keyword.upper():
        if char in seen:
            analysis['duplicates'].append(char)
        seen.add(char)

    # Determine strength
    if analysis['length'] >= 8 and len(analysis['duplicates']) == 0:
        analysis['strength'] = 'strong'
    elif analysis['length'] >= 6 and len(analysis['duplicates']) <= 1:
        analysis['strength'] = 'medium'

    return analysis

# Usage example
keywords = ['SECRET', 'CRYPTOGRAPHY', 'ZEBRA', 'SUPERCALIFRAGILISTICEXPIALIDOCIOUS']
for keyword in keywords:
    strength = analyze_keyword_strength(keyword)
    print(f"{keyword}: {strength['strength']} "
          f"(Length: {strength['length']}, "
          f"Duplicates: {len(strength['duplicates'])})")
频率分析工具
def frequency_analysis(text):
    """Perform frequency analysis on text."""
    from collections import Counter
    import string

    # Clean text (letters only)
    clean_text = ''.join(char.upper() for char in text if char.isalpha())

    # Count frequencies
    letter_counts = Counter(clean_text)
    total_letters = len(clean_text)

    # Calculate percentages
    frequencies = {}
    for letter in string.ascii_uppercase:
        count = letter_counts.get(letter, 0)
        frequencies[letter] = (count / total_letters) * 100 if total_letters > 0 else 0

    # Sort by frequency
    sorted_freq = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)

    return sorted_freq, total_letters

# English language frequency reference
ENGLISH_FREQ = {
    'E': 12.7, 'T': 9.1, 'A': 8.2, 'O': 7.5, 'I': 7.0, 'N': 6.7,
    'S': 6.3, 'H': 6.1, 'R': 6.0, 'D': 4.3, 'L': 4.0, 'C': 2.8
}

def compare_with_english(text_frequencies):
    """Compare text frequencies with standard English."""
    comparison = []
    for letter, freq in text_frequencies[:12]:  # Top 12 letters
        english_freq = ENGLISH_FREQ.get(letter, 0)
        difference = abs(freq - english_freq)
        comparison.append((letter, freq, english_freq, difference))

    return comparison

互动学习示例

渐进难度示例
初级

关键词:CAT 明文:I LOVE CATS 特点:简单的 3 字母关键词,易于理解

中级

关键词:JAVASCRIPT 明文:Programming is fun and educational 挑战:带有需要去除的重复字母的较长关键词

高级

关键词:CRYPTANALYSIS 明文:Frequency analysis reveals patterns in monoalphabetic substitution ciphers 复杂性:技术词汇和较长的文本,用于真实的分析

历史案例研究
案例 1:苏格兰玛丽女王(1586 年)

历史背景:巴宾顿阴谋通信 关键词:MARIE(简化示例) 原始消息:"The deed will be done on Thursday" 加密:"Rdj kjjk vpmm yj kghj gh Rdqxakit"

历史注释:实际使用的密码更为复杂,但基于关键词的替换是命名密码本(nomenclator)系统的一个组成部分,该系统最终导致了玛丽的覆灭。

案例 2:电报时代(1850 年代)

商业背景:商业通信 关键词:TELEGRAPH 成本考量:较短的加密消息节省了资金 示例:"PROFITS UP" → "QUHDITJ RQ"

实践练习

练习 1:基础实现

使用你的名字作为关键词,创建关键词密码并加密一条个人消息。

练习 2:强度比较

比较这些关键词生成的密码字母表:

  • SHORT
  • MEDIUM
  • VERYLONGKEYWORD

分析关键词长度如何影响替换模式。

练习 3:破解练习

尝试破解这个关键词密码: 密文:"MJKKP VPEKX! LPHJ YGPJFKXJ FP XJVJEHJFJ QGJ JFXEFJ GRA FPQGJHKJX HGJAKJ"

提示

  • 常见英文文本
  • 关键词是一个常用的 6 字母词
  • 寻找出现频率最高字母的模式
练习 4:算法优化

实现一个处理以下情况的版本:

  • 多个关键词(在它们之间轮换)
  • 非英文字母表
  • 数字保留选项

最佳实践

安全注意事项
  1. 关键词选择:使用无重复字母的长随机关键词
  2. 消息长度:较短的消息更难分析
  3. 上下文感知:考虑攻击者可能获得的信息
实现指南
  1. 输入验证:始终验证和净化关键词输入
  2. 大小写处理:一致地决定如何处理大小写
  3. 错误处理:管理空关键词或特殊字符等边界情况
  4. 性能:对于大型文本,优化映射查找
教育应用
  1. 渐进学习:从简单示例开始,逐步增加复杂性
  2. 视觉辅助:清晰显示字母映射
  3. 互动工具:允许学生实验不同的关键词
  4. 历史背景:将示例与真实的历史用途联系起来

关键词密码是密码学概念的绝佳入门,同时提供实际的编程挑战。这些示例展示了理解古典替换密码的历史和教育背景所需的实现细节和分析技术。