java实现维吉尼亚算法
时间: 2023-10-27 08:37:47 浏览: 34
以下是Java实现维吉尼亚算法的示例代码:
public class VigenereCipher {
private String key;
public VigenereCipher(String key) {
this.key = key;
}
public String encrypt(String plainText) {
StringBuilder encryptedText = new StringBuilder();
for (int i = 0, j = 0; i < plainText.length(); i++) {
char c = plainText.charAt(i);
if (c < 'A' || c > 'Z') {
continue;
}
encryptedText.append((char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A'));
j = ++j % key.length();
}
return encryptedText.toString();
}
public String decrypt(String encryptedText) {
StringBuilder plainText = new StringBuilder();
for (int i = 0, j = 0; i < encryptedText.length(); i++) {
char c = encryptedText.charAt(i);
if (c < 'A' || c > 'Z') {
continue;
}
plainText.append((char) ((c - key.charAt(j) + 26) % 26 + 'A'));
j = ++j % key.length();
}
return plainText.toString();
}
public static void main(String[] args) {
VigenereCipher cipher = new VigenereCipher("SECRETKEY");
String plainText = "HELLO WORLD";
String encryptedText = cipher.encrypt(plainText);
String decryptedText = cipher.decrypt(encryptedText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decryptedText);
}
}
在这个示例中,我们定义了一个VigenereCipher类,该类包含一个构造函数来初始化密钥,以及两个方法encrypt()和decrypt()来加密和解密字符串。encrypt()方法将明文转换为密文,而decrypt()方法将密文转换回明文。在这里,我们使用了Vigenere算法的基本原理-使用密钥对明文进行多次Caesar加密,每个字符使用不同的Caesar密码。这里我们假设密钥只包含大写字母,并且明文只包含大写字母。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)