我无法捕获此代码的异常。查看代码注释中的线索。显然序列化工作正常,所以我不会粘贴序列化方法代码。
public class NewCipher {
private static final String password = "somestatickey";
private Cipher desCipher;
private SecretKey secretKey;
private Context ctx;
public NewCipher(Context ctx) throws Exception {
this.ctx = ctx;
// Create Key
byte key[] = password.getBytes();
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
secretKey = keyFactory.generateSecret(desKeySpec);
// Create Cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
}
棘手的部分从这里开始:
public ArrayList<Category> loadCategories(){
try {
try {
// Change cipher mode
desCipher.init(Cipher.DECRYPT_MODE, secretKey); //some uncatchable exception seems to be appearing here
// Create stream
FileInputStream fis;
fis = ctx.openFileInput("categories.des");
BufferedInputStream bis = new BufferedInputStream(fis);
CipherInputStream cis = new CipherInputStream(bis, desCipher);
ObjectInputStream ois = new ObjectInputStream(cis);
try {
// Read objects
ArrayList<Category> categories = (ArrayList<Category>) ois.readObject(); //however the debugger goes right to this line and then goes to the finally, and then straight to final catch block
return categories; //not beeing executed
}
finally {
ois.close(); //debugger does a step here and then jumps to the end
}
}
catch(GeneralSecurityException ex) {
Log.v("Debug", "Some message", ex); //not beeing executed
return null; //not beeing executed
}
} catch (Exception e) {
Log.v("Debug", "Some message", e); //not beeing executed
return null; //actually the debugger jumps right here avoiding the log line above
}
}
我如何知道问题在desCipher.init(Cipher.DECRYPT_MODE, secretKey);
行?我一个接一个地删除行,并且总是得到相同的结果。第一行肯定发生了一些错误。
不幸的是,我无法抓住它,并且由于某种原因,代码正在尝试进一步执行。我在这里完全糊涂了。我尝试IOException
和IllegalStateException
代替GeneralSecurityException
。还试图抛出BadPaddingException。虽然没有日志。
拜托,我需要帮助。
答案 0 :(得分:0)
您的密钥大小不正确,代码应抛出InvalidKeyException
,其类型为GeneralSecurityException。在调试之前,请确保您的代码编译并与生成的类文件保持同步。
请注意,永远不要使用String作为密码,不应该使用getBytes()而不指定编码,不应该使用DES,不应该使用ECB模式(等等)。