维吉尼亚密码
时间: 2025-06-18 13:55:41 浏览: 3
### 维吉尼亚密码的加密解密方法及其实现原理
维吉尼亚密码是一种多表替换密码,其核心思想是通过一个密钥对明文进行加密,使得每个字符根据密钥的不同部分被映射到不同的替换表中。这种加密方式相较于简单的凯撒密码更加复杂和安全。
#### 1. 加密原理
在维吉尼亚密码中,加密过程基于字母的偏移量计算。具体来说,明文中的每个字母与密钥中的对应字母结合,通过模运算生成密文。如果密钥长度小于明文,则密钥会循环使用[^1]。
加密公式如下:
\[ C_i = (P_i + K_i) \mod 26 \]
其中:
- \( P_i \) 是明文中第 \( i \) 个字母的位置(A=0, B=1, ..., Z=25)。
- \( K_i \) 是密钥中第 \( i \) 个字母的位置。
- \( C_i \) 是生成的密文中第 \( i \) 个字母的位置。
例如,若明文为 "I LOVE YOU",密钥为 "KEY",则加密过程可以通过查找密码表或直接计算完成。
```python
def vigenere_encrypt(plaintext, key):
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ciphertext = ''
key_length = len(key)
for i in range(len(plaintext)):
if plaintext[i].isalpha():
p_index = alphabet.find(plaintext[i].upper())
k_index = alphabet.find(key[i % key_length].upper())
c_index = (p_index + k_index) % 26
ciphertext += alphabet[c_index]
else:
ciphertext += plaintext[i]
return ciphertext
```
#### 2. 解密原理
解密过程是加密的逆操作,通过从密文中减去密钥对应的偏移量来还原明文。
解密公式如下:
\[ P_i = (C_i - K_i + 26) \mod 26 \]
其中:
- \( C_i \) 是密文中第 \( i \) 个字母的位置。
- \( K_i \) 是密钥中第 \( i \) 个字母的位置。
- \( P_i \) 是还原后的明文中第 \( i \) 个字母的位置。
```python
def vigenere_decrypt(ciphertext, key):
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
plaintext = ''
key_length = len(key)
for i in range(len(ciphertext)):
if ciphertext[i].isalpha():
c_index = alphabet.find(ciphertext[i].upper())
k_index = alphabet.find(key[i % key_length].upper())
p_index = (c_index - k_index + 26) % 26
plaintext += alphabet[p_index]
else:
plaintext += ciphertext[i]
return plaintext
```
#### 3. Java 实现示例
以下是一个完整的 Java 示例代码,用于实现维吉尼亚密码的加密和解密:
```java
public class VigenereCipher {
public static String encrypt(String plaintext, String key) {
StringBuilder ciphertext = new StringBuilder();
int keyLength = key.length();
for (int i = 0; i < plaintext.length(); i++) {
char pChar = plaintext.charAt(i);
if (Character.isLetter(pChar)) {
char kChar = key.charAt(i % keyLength);
char cChar = (char) (((Character.toUpperCase(pChar) - 'A' + Character.toUpperCase(kChar) - 'A') % 26 + 'A'));
ciphertext.append(cChar);
} else {
ciphertext.append(pChar);
}
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, String key) {
StringBuilder plaintext = new StringBuilder();
int keyLength = key.length();
for (int i = 0; i < ciphertext.length(); i++) {
char cChar = ciphertext.charAt(i);
if (Character.isLetter(cChar)) {
char kChar = key.charAt(i % keyLength);
char pChar = (char) (((Character.toUpperCase(cChar) - 'A' - (Character.toUpperCase(kChar) - 'A') + 26) % 26 + 'A'));
plaintext.append(pChar);
} else {
plaintext.append(cChar);
}
}
return plaintext.toString();
}
public static void main(String[] args) {
String plaintext = "ILOVEYOU";
String key = "KEY";
String ciphertext = encrypt(plaintext, key);
System.out.println("密文是: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
System.out.println("明文是: " + decryptedText);
}
}
```
#### 4. 注意事项
- 明文和密钥应全部使用大写字母[^3],以确保计算的一致性。
- 如果密钥包含非字母字符,需要对其进行预处理以避免计算错误。
- 密钥长度较短时,密码的安全性较低,容易受到频率分析攻击。
阅读全文
相关推荐







