【发布时间】:2018-01-10 13:56:58
【问题描述】:
对不起,如果我的问题很愚蠢,但我正在学习 java,我正在做一个需要加密和解密的项目,我已经完成了代码,加密按钮功能齐全但是当我尝试解密时(不同的按钮)一直有错误。
加密代码
path = chooser.getSelectedFile();
String x = path.toString();
try {
Scanner scanner = new Scanner(new File(x));
content = scanner.useDelimiter("\\Z").next();
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("DES");
byte[] text = content.getBytes("UTF8");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(text);
String s = new String(textEncrypted);
try {
File statText = new File(x);
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write(s);
w.close();
}
catch (IOException e3) {
JOptionPane.showMessageDialog(null, "something is wrong with the txt file");
}
}catch(Exception e1)
{
System.out.println("En");
}
这里是解密部分:
path = chooser.getSelectedFile();
String x = path.toString();
try {
Scanner scanner = new Scanner(new File(x));
content = scanner.useDelimiter("\\Z").next();
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("DES");
byte[] text = content.getBytes("UTF8");
byte[] textEncrypted = desCipher.doFinal(text);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
String s = new String(textDecrypted);
System.out.println(s);
}catch(Exception e1)
{
System.out.println("De"); /* here we go this is my error*/
}
第二个代码“catch(Exception e1)”的错误
【问题讨论】:
-
那么你得到了什么错误?
-
您需要查看异常对象,它会告诉您确切的问题所在。您也不应该使用 DES,因为它不被认为是安全的。
-
你贴了两个代码块,第一个是加密,第二个是加密和解密。哪个部分出错了?
-
@OcelotcR 第二个代码 Exception e1 at the comment
-
"De" 不是错误,它是一个无意义的字符串。将 System.out.println 替换为 e1.printStackTrace();
标签: java encryption utf-8 cryptography des