维吉尼亚算法java
时间: 2023-12-06 11:37:35 浏览: 34
以下是使用Java实现维吉尼亚算法的示例代码:
```java
public class VigenereCipher {
private final String key;
public VigenereCipher(String key) {
this.key = key;
}
public String encrypt(String plaintext) {
String ciphertext = "";
plaintext = plaintext.toUpperCase();
for (int i = 0, j = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
if (c < 'A' || c > 'Z') {
continue;
}
ciphertext += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
j = ++j % key.length();
}
return ciphertext;
}
public String decrypt(String ciphertext) {
String plaintext = "";
ciphertext = ciphertext.toUpperCase();
for (int i = 0, j = 0; i < ciphertext.length(); i++) {
char c = ciphertext.charAt(i);
if (c < 'A' || c > 'Z') {
continue;
}
plaintext += (char) ((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return plaintext;
}
}
```
使用示例:
```java
public static void main(String[] args) {
String plaintext = "HELLO WORLD";
String key = "SECRET";
VigenereCipher cipher = new VigenereCipher(key);
String ciphertext = cipher.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext); // 输出:KSGDQ XQZLK
String decryptedText = cipher.decrypt(ciphertext);
System.out.println("Decrypted text: " + decryptedText); // 输出:HELLO WORLD
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)