仿射密码示例和教程

通过详细示例和可运行代码学习仿射密码

Basic Encryption Examples

Simple Word Encryption

a = 5b = 8

Phrase Encryption

a = 5b = 8

Different Keys

a = 7b = 3

Identity Cipher (a=1)

a = 1b = 3

Python Implementation

def gcd(a, b):
    """Calculate Greatest Common Divisor using Euclidean algorithm"""
    while b:
        a, b = b, a % b
    return a

def mod_inverse(a, m):
    """Calculate modular multiplicative inverse using Extended Euclidean Algorithm"""
    if gcd(a, m) != 1:
        raise ValueError(f"{a} and {m} are not coprime")

    m0 = m
    x0, x1 = 0, 1

    while a > 1:
        q = a // m
        a, m = m, a % m
        x0, x1 = x1 - q * x0, x0

    return x1 + m0 if x1 < 0 else x1

def affine_encrypt(text, a, b):
    """Encrypt text using Affine cipher: E(x) = (ax + b) mod 26"""
    result = []

    for char in text:
        if char.isupper():
            x = ord(char) - ord('A')
            encrypted = (a * x + b) % 26
            result.append(chr(encrypted + ord('A')))
        elif char.islower():
            x = ord(char) - ord('a')
            encrypted = (a * x + b) % 26
            result.append(chr(encrypted + ord('a')))
        else:
            result.append(char)

    return ''.join(result)

def affine_decrypt(text, a, b):
    """Decrypt text using Affine cipher: D(y) = a⁻¹(y - b) mod 26"""
    a_inv = mod_inverse(a, 26)
    result = []

    for char in text:
        if char.isupper():
            y = ord(char) - ord('A')
            decrypted = (a_inv * (y - b)) % 26
            result.append(chr(decrypted + ord('A')))
        elif char.islower():
            y = ord(char) - ord('a')
            decrypted = (a_inv * (y - b)) % 26
            result.append(chr(decrypted + ord('a')))
        else:
            result.append(char)

    return ''.join(result)

# Example usage
plaintext = "HELLO"
a, b = 5, 8

ciphertext = affine_encrypt(plaintext, a, b)
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext}")
print(f"Decrypted: {affine_decrypt(ciphertext, a, b)}")

Features: This implementation includes GCD calculation, modular inverse computation using the Extended Euclidean Algorithm, and both encryption and decryption functions with full error handling.

Practice Problems

Encrypt "CRYPTOGRAPHY" using a=3, b=5
Decrypt "WJPPJ" with a=5, b=8
What is the modular inverse of 7 (mod 26)?

Complete Tutorial

Understanding the Affine Cipher

The Affine cipher uses a mathematical function to encrypt text. Each letter is converted to a number (A=0, B=1, ..., Z=25), then transformed using:

E(x) = (ax + b) mod 26

Where:

  • x is the position of the plaintext letter (0-25)
  • a is the multiplicative key (must be coprime with 26)
  • b is the additive key (0-25)
  • mod 26 ensures the result stays within the alphabet

Why Must 'a' Be Coprime with 26?

The value of 'a' must be coprime with 26 (GCD(a, 26) = 1) to ensure every letter maps to a unique letter. If 'a' shares a common factor with 26, multiple letters would encrypt to the same letter, making decryption impossible.

Valid values for 'a': 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25

Decryption Formula

To decrypt, we need the modular inverse of 'a' (denoted a⁻¹):

D(y) = a⁻¹(y - b) mod 26

仿射密码示例

通过实际示例学习仿射密码(Affine Cipher)更为直观。本页面提供逐步加密和解密演示、完整的 Python 代码以及用于检验理解程度的练习题。

基础加密示例

使用密钥 A=5,B=8 对单词"HELLO"进行加密:

第一步: 将字母转换为数字(A=0,B=1,……Z=25)

  • H=7,E=4,L=11,L=11,O=14

第二步: 应用加密公式 E(x) = (5x + 8) mod 26

  • H:(5×7 + 8) mod 26 = 43 mod 26 = 17 = R
  • E:(5×4 + 8) mod 26 = 28 mod 26 = 2 = C
  • L:(5×11 + 8) mod 26 = 63 mod 26 = 11 = L
  • L:(5×11 + 8) mod 26 = 63 mod 26 = 11 = L
  • O:(5×14 + 8) mod 26 = 78 mod 26 = 0 = A

结果: HELLO → RCLLA

解密示例

使用 A=5,B=8 解密"RCLLA",需要先求5 mod 26的模逆元,结果为21。

第一步: 应用解密公式 D(y) = 21(y - 8) mod 26

  • R(17):21×(17-8) mod 26 = 21×9 mod 26 = 189 mod 26 = 7 = H
  • C(2):21×(2-8) mod 26 = 21×(-6) mod 26 = 21×20 mod 26 = 420 mod 26 = 4 = E
  • L(11):21×(11-8) mod 26 = 21×3 mod 26 = 63 mod 26 = 11 = L
  • L(11):21×(11-8) mod 26 = 21×3 mod 26 = 63 mod 26 = 11 = L
  • A(0):21×(0-8) mod 26 = 21×(-8) mod 26 = 21×18 mod 26 = 378 mod 26 = 14 = O

结果: RCLLA → HELLO

Python 实现

以下是仿射密码的完整 Python 实现:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def mod_inverse(a, m):
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    return None

def affine_encrypt(plaintext, a, b):
    if gcd(a, 26) != 1:
        raise ValueError("密钥 'a' 必须与26互质")

    result = []
    for char in plaintext.upper():
        if char.isalpha():
            x = ord(char) - ord('A')
            encrypted = (a * x + b) % 26
            result.append(chr(encrypted + ord('A')))
        else:
            result.append(char)
    return ''.join(result)

def affine_decrypt(ciphertext, a, b):
    if gcd(a, 26) != 1:
        raise ValueError("密钥 'a' 必须与26互质")

    a_inv = mod_inverse(a, 26)
    result = []
    for char in ciphertext.upper():
        if char.isalpha():
            y = ord(char) - ord('A')
            decrypted = (a_inv * (y - b)) % 26
            result.append(chr(decrypted + ord('A')))
        else:
            result.append(char)
    return ''.join(result)

# 使用示例
plaintext = "HELLO WORLD"
a, b = 5, 8
encrypted = affine_encrypt(plaintext, a, b)
decrypted = affine_decrypt(encrypted, a, b)
print(f"明文: {plaintext}")
print(f"加密: {encrypted}")
print(f"解密: {decrypted}")

练习题

通过以下练习检验您的理解:

题目1: 使用 A=7,B=3 加密"ATTACK"

题目2: 使用 A=3,B=5 解密"FGXOT"

题目3: 求7 mod 26的模逆元

题目4: 使用 A=11,B=15 加密"CIPHER"

题目5: 密钥 A 的所有有效值是哪些?

答案

  1. ATTACK → EZZHFP
  2. FGXOT → HELLO
  3. 7 mod 26的模逆元是15(因为 7×15 = 105 = 4×26 + 1)
  4. CIPHER → AFLWPC
  5. 有效 A 值:1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25

可以在我们的仿射密码工具中验证这些示例,或使用计算器验证模逆元。

常见问题

如何计算模逆元?

A mod 26的模逆元是一个数 A⁻¹,满足 (A × A⁻¹) mod 26 = 1。您可以通过测试1到25之间的数字找到它,或使用扩展欧几里得算法。我们的计算器可以自动计算。

使用无效的 A 值会怎样?

如果 A 与26有公因数(如2, 4, 6, 8, 10, 12, 13等),多个明文字母会映射到同一密文字母,使解密变为不可能。

仿射密码可以用其他编程语言实现吗?

可以!该算法在任何编程语言中都适用。关键操作是模运算(% 运算符)和求模逆元。请参考上面的 Python 示例作为参考。

仿射密码与凯撒密码有什么关系?

凯撒密码是仿射密码 A=1 时的特例。这将公式简化为 E(x) = (x + b) mod 26,即简单的移位操作。