java实现维吉尼亚密码加解密算法(附完整源码)
时间: 2023-12-07 20:22:15 浏览: 207
以下是Java实现维吉尼亚密码加解密算法的完整源码:
```java
import java.util.Scanner;
public class VigenereCipher {
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取明文和密钥
System.out.print("请输入明文:");
String plainText = scanner.nextLine().toUpperCase();
System.out.print("请输入密钥:");
String key = scanner.nextLine().toUpperCase();
// 加密
String cipherText = encrypt(plainText, key);
System.out.println("加密后的密文为:" + cipherText);
// 解密
String decryptedText = decrypt(cipherText, key);
System.out.println("解密后的明文为:" + decryptedText);
scanner.close();
}
/**
* 维吉尼亚密码加密
*
* @param plainText 明文
* @param key 密钥
* @return 密文
*/
public static String encrypt(String plainText, String key) {
StringBuilder cipherText = new StringBuilder();
int keyIndex = 0;
for (char c : plainText.toCharArray()) {
if (Character.isLetter(c)) {
int plainTextIndex = ALPHABET.indexOf(c);
int keyCharIndex = ALPHABET.indexOf(key.charAt(keyIndex));
int cipherTextIndex = (plainTextIndex + keyCharIndex) % ALPHABET.length();
cipherText.append(ALPHABET.charAt(cipherTextIndex));
keyIndex = ++keyIndex % key.length();
} else {
cipherText.append(c);
}
}
return cipherText.toString();
}
/**
* 维吉尼亚密码解密
*
* @param cipherText 密文
* @param key 密钥
* @return 明文
*/
public static String decrypt(String cipherText, String key) {
StringBuilder plainText = new StringBuilder();
int keyIndex = 0;
for (char c : cipherText.toCharArray()) {
if (Character.isLetter(c)) {
int cipherTextIndex = ALPHABET.indexOf(c);
int keyCharIndex = ALPHABET.indexOf(key.charAt(keyIndex));
int plainTextIndex = (cipherTextIndex - keyCharIndex + ALPHABET.length()) % ALPHABET.length();
plainText.append(ALPHABET.charAt(plainTextIndex));
keyIndex = ++keyIndex % key.length();
} else {
plainText.append(c);
}
}
return plainText.toString();
}
}
```
使用时,只需在主函数中调用 `encrypt` 和 `decrypt` 方法即可。注意,这里使用的是大写字母表,如果要支持小写字母,可以在字母表中添加小写字母即可。
阅读全文