我在作业中感到困惑:D 给定一个 UML 图,我必须实现一个类(class)管理应用程序,其中一部分是 Student 类,如下
public class Student extends Person implements Encryptable {
private String program;
private Vector<Course> courses;
//constructor.
public Student(String Name, String pnr, String tel, String prog) {
super(Name, pnr, tel);
program = prog;
courses = new Vector<Course>();
}
/* implementation of related methods
...... */
@Override
public void encrypt(String password) {
}
@Override
public void decrypt(String password) {
}
所有其他类以及该类的所有相关 setter 和 getter 都已实现,Encryptable 接口(interface)如下
public interface Encryptable {
public void encrypt(String password);
public void decrypt(String password);
}
在之前的任务中,我实现了一个“PassworCrypter”类,我应该使用该类
public class PasswordCrypter {
Cipher ecipher;
Cipher dcipher;
SecretKey key;
DESKeySpec dks;
SecretKeyFactory skf;
byte[] psword;
public PasswordCrypter(String password) {
try {
psword = password.getBytes("UTF-16");
dks = new DESKeySpec(psword);
skf = SecretKeyFactory.getInstance("DES");
key = skf.generateSecret(dks);
ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (NoSuchAlgorithmException e) {
throw new CrypterException(e);
} catch (NoSuchPaddingException e) {
throw new CrypterException(e);
} catch (InvalidKeyException e) {
throw new CrypterException(e);
} catch (InvalidKeySpecException e) {
throw new CrypterException(e);
} catch (UnsupportedEncodingException e) {
throw new CrypterException(e);
}
}
public byte[] encrypt(byte[] array) {
try {
return ecipher.doFinal(array);
} catch (IllegalBlockSizeException e) {
throw new CrypterException(e);
} catch (BadPaddingException e) {
throw new CrypterException(e);
}
}
public byte[] decrypt(byte[] array) {
try {
return dcipher.doFinal(array);
} catch (IllegalBlockSizeException e) {
throw new CrypterException(e);
} catch (BadPaddingException e) {
throw new CrypterException(e);
}
}
}
我应该在学生的本地和继承字段上使用PasswordCrypter类 类(class)。当 Student 对象被加密时,应该无法获取数据 比如学生的名字,无需先调用解密。 Student 对象应该 除非您需要访问其任何数据,否则始终进行加密。 谁能给我一个想法或告诉我应该如何加密这个该死的学生:)
最佳答案
我认为您在Encryptable
方面遇到问题。该方法的签名应该是
public void encrypt(Encrypter enc);
public void decrypt(Decrypter dec);
您可以在其中定义两个单独的接口(interface)Encrypter
和Decrypter
。所以最后你可以使用PasswordCrypter
作为实现这两个方法的中心类。
public class PasswordCrypter implements Encrypter,Decrypter {
所以现在在你的学生类(class)中你可以这样做
public void encrypt(Encrypter enc) {
byte[] programbytes = enc.encrypt(program);
}
public void encrypt(Decrypter dec) {
program = dec.decrypt(programbytes);
}
关于java - 通过自行实现的 crypter 类加密和解密对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989107/