vigenere密码算法java
时间: 2023-10-12 21:16:46 浏览: 107
以下是 Vigenere 密码算法的 Java 实现:
```java
public class VigenereCipher {
private 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;
}
public static void main(String[] args) {
VigenereCipher cipher = new VigenereCipher("SECRETKEY");
String plaintext = "HELLO WORLD";
String ciphertext = cipher.encrypt(plaintext);
System.out.println(ciphertext);
System.out.println(cipher.decrypt(ciphertext));
}
}
```
其中,构造函数 `VigenereCipher(String key)` 接受一个密钥,`encrypt(String plaintext)` 方法将明文加密为密文,`decrypt(String ciphertext)` 方法将密文解密为明文。在加密和解密过程中,只对大写字母进行操作,忽略其他字符。
阅读全文