有没有一种方法可以用java中的单个方法对给定密钥的消息进行加密和解密?

时间:2020-03-09 04:02:37

标签: java encryption caesar-cipher

我是编程新手,过去只做过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;
}
}

我的讲师还向我提到,编码和解码本质上是相同的操作,但带有反向键。我相信“旋转”方法应该既可以通过给定的密钥加密也可以解密给定的文本。相反,我只设法用给定的密钥对给定文本进行加密,但是我完全不知道如何用这种相同的方法进行相反的操作。我有办法做到这一点吗?应该进行哪些更改?

0 个答案:

没有答案
相关问题