单表置换密码java代码实现_单表替换密码
时间: 2023-11-18 07:04:19 浏览: 37
以下是一个简单的单表置换密码的Java代码实现:
```java
public class MonoalphabeticCipher {
private String key;
public MonoalphabeticCipher(String key) {
this.key = key;
}
public String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder();
for (char c : plaintext.toCharArray()) {
if (Character.isLetter(c)) {
int position = Character.toUpperCase(c) - 'A';
ciphertext.append(Character.isUpperCase(c) ? Character.toUpperCase(key.charAt(position)) : Character.toLowerCase(key.charAt(position)));
} else {
ciphertext.append(c);
}
}
return ciphertext.toString();
}
public String decrypt(String ciphertext) {
StringBuilder plaintext = new StringBuilder();
for (char c : ciphertext.toCharArray()) {
if (Character.isLetter(c)) {
int position = key.toUpperCase().indexOf(Character.toUpperCase(c));
plaintext.append(Character.isUpperCase(c) ? Character.toUpperCase((char) ('A' + position)) : Character.toLowerCase((char) ('a' + position)));
} else {
plaintext.append(c);
}
}
return plaintext.toString();
}
}
```
使用方法:
```java
MonoalphabeticCipher cipher = new MonoalphabeticCipher("qwertyuiopasdfghjklzxcvbnm");
String plaintext = "Hello, world!";
String ciphertext = cipher.encrypt(plaintext);
String decryptedPlaintext = cipher.decrypt(ciphertext);
System.out.println(ciphertext); // "Ittqj, itlja!"
System.out.println(decryptedPlaintext); // "Hello, world!"
```
其中,构造函数中的参数`key`是一个由26个字母组成的字符串,表示明文字母到密文字母的映射关系。`encrypt`方法将明文字符串转换为密文字符串,`decrypt`方法将密文字符串转换为明文字符串。