java - 有没有办法让我在java中的单一方法中加密和解密给定密钥的消息?
问题描述
我是编程新手,过去只做过 Python。目前,我正在从事一项大学作业,要求我实施凯撒密码。首先,给了我一个名为“Cipher”的接口,并负责编写一个名为“RotationCipher”的类来实现这个接口。
界面:
public interface Cipher {
/**
* Encodes the given plain text into a secret cipher text
*
* @param plainText the plain text to encode
* @return the cipher text
*/
abstract public String encrypt(String plainText);
/**
* Determines the plain text string for a given cipher text.
*
* @param cipherText the cipher text to decode
* @return the plain text original
*/
abstract public String decrypt(String cipherText);
}
实现接口的类RotationCipher:
abstract class RotationCipher implements Cipher {
protected int shift;
public RotationCipher(int key) {
shift = key;
}
protected String text;
protected abstract String rotate(int shift, String text);
public String encrypt(String plainText) {
String cipherText = rotate(shift, plainText);
return cipherText;
}
public String decrypt(String cipherText) {
shift = shift - 26;
String plainText = rotate(shift, cipherText);
return plainText;
}
}
继承自 RotationCipher 类的子类 CaesarCipher(用于加密和解密给定密钥的消息):
public class CaesarCipher extends RotationCipher{
public CaesarCipher(int key){
super (key);
}
public String rotate(int shift, String text) {
String cipherTxt = "";
String plainTxt = "";
if(shift>26) {
shift = shift%26;
}else if(shift < 0) {
shift = (shift%26) + 26;
}
int length = text.length();
for(int i = 0; i < length; i++) {
char ch = text.charAt(i);
if(Character.isLetter(ch)) {
if(Character.isLowerCase(ch)) {
char c = (char)(ch + shift);
if(c > 'z') {
cipherTxt = cipherTxt + (char)(ch - (26 - shift));
}else {
cipherTxt = cipherTxt + c;
}
}else if(Character.isUpperCase(ch)) {
char c = (char)(ch + shift);
if(c > 'Z') {
cipherTxt = cipherTxt + (char)(ch - (26 - shift));
}else if(ch == 'X') {
cipherTxt = cipherTxt + (char)(ch -(26 - shift));
}
else {
cipherTxt = cipherTxt + c;
}
}
}else if(Character.isLetter(ch) == false) {
cipherTxt = cipherTxt + ch;
}
}
return cipherTxt;
}
}
我的讲师还向我提到,编码和解码本质上是相同的操作,但使用的是反转键。我相信“旋转”方法应该通过给定的密钥加密和解密给定的文本。相反,我只设法用给定的密钥加密了给定的文本,但我完全不知道如何用同样的方法做相反的事情。有没有办法让我做到这一点,应该做出哪些改变?
解决方案
推荐阅读
- amazon-web-services - Grafana 中的 Kubernetes Istio 延迟路径明智
- sequelize.js - Feathers-Sequelize : belongsToMany 或 belongsTo... 创建关联
- vue.js - Vuejs弹出菜单:在页面底部附近发生右键单击时应用CSS转换
- c - 我们什么时候应该在 char 数组(char [])上使用 char 指针(char *)?
- swift - 我在比较 Swift 中的字符串时遇到问题
- cloudinary - Cloudinary 上传图像小部件无法按预期工作
- java - 单击提交后代码未运行,显示 404。我在我的桌面上写了类似的代码,它正在运行。谁能帮我吗
- web-bluetooth - Windows Chrome 上的网络蓝牙的 20 字节 MTU?
- python-3.x - 使用 pyqtgraph 实时更新条形图
- mysql - 如何将一个表中的两对与 MySQL 上另一个表中的两对进行比较