Java实现恩尼格码密码机的加密和解密
时间: 2023-08-11 08:07:55 浏览: 118
恩尼格码密码机是一种简单的替换密码,它使用一个密钥表来将明文字符替换为密文字符。Java可以很容易地实现这个密码机的加密和解密过程。以下是一个示例程序:
```java
import java.util.HashMap;
import java.util.Map;
public class EnigmaCipher {
private Map<Character, Character> keyTable;
public EnigmaCipher(String key) {
keyTable = new HashMap<>();
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < alphabet.length(); i++) {
char c = alphabet.charAt(i);
char k = key.charAt(i);
keyTable.put(c, k);
}
}
public String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
if (Character.isUpperCase(c)) {
c = keyTable.get(c);
}
ciphertext.append(c);
}
return ciphertext.toString();
}
public String decrypt(String ciphertext) {
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < ciphertext.length(); i++) {
char c = ciphertext.charAt(i);
if (Character.isUpperCase(c)) {
for (Map.Entry<Character, Character> entry : keyTable.entrySet()) {
if (entry.getValue() == c) {
c = entry.getKey();
break;
}
}
}
plaintext.append(c);
}
return plaintext.toString();
}
public static void main(String[] args) {
String key = "QWERTYUIOPASDFGHJKLZXCVBNM";
EnigmaCipher cipher = new EnigmaCipher(key);
String plaintext = "HELLO WORLD";
String ciphertext = cipher.encrypt(plaintext);
String decryptedText = cipher.decrypt(ciphertext);
System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext: " + ciphertext);
System.out.println("Decrypted text: " + decryptedText);
}
}
```
在这个示例程序中,我们创建了一个 `EnigmaCipher` 类,它接受一个密钥表作为构造函数的参数。`encrypt()` 方法接受明文字符串并返回密文字符串,`decrypt()` 方法接受密文字符串并返回明文字符串。我们还提供了一个 `main()` 方法来演示如何使用这个类。
阅读全文