我是一名大四的学生,放假前老师布置课程设计,可是我用java编程,老师说他不会java,要我自己解决,天哪麻烦大家帮我看看程序啊...我的题目是文件的加密解密,我加密已经搞定,可是解密就会把文件清空,实在不知道是什么原因。好像是从文件读出来的密钥有问题,可是程序又不报错!敬请各位大虾帮帮小女子忙吧...  
 代码如下:(代码很乱,写的也不简洁,大家见谅哟...^_^)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.crypto.*;
import javax.crypto.Cipher;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.applet.*;
import java.lang.*;public class keySecurity extends Frame
{
static String DirName;
static String FileName;
static String s1;
static String s2;
public keySecurity()
{
setTitle("02级计算机1班 姓名:查继华 学号:02081001 课程设计");
this.setLayout(new FlowLayout());
this.setSize(400,800);
Label l1=new Label("请选择要操作的文件:");
add(l1);
final TextField tf1=new TextField(50);
add(tf1);
Button b1=new Button("打开");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//点击打开按钮,应该出现一个对话框,对话框的功能是让用户选择
//要打开的文件
FileDialog fd=new FileDialog(keySecurity.this,"选择要操作的文件",FileDialog.LOAD);
fd.show();
DirName=fd.getDirectory();//获取用户选定的文件名路径
FileName=fd.getFile();//获取用户选定的文件名
tf1.setText(DirName+FileName);
}
});
add(b1);
Button b2=new Button("加密");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//弹出一个对话框,让用户输入密码,再次确认密码,还有确定,
//取消按钮,点确定后,开始加密!!!若文件已经是加密过的
//则弹出对话框,提示已经加密的文件!
//再弹出个对话框,告诉用户加密成功,密码为***。
File f1=new File("key"+FileName+".txt");
if(f1.exists())
{//文件已经加密过
Dialog dog=new Dialog(keySecurity.this,"提示窗口",false);
Label lbl=new Label("你要加密的文件已经加密过了,点确定退出程序");
Button btn=new Button("确定");
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
dog.setLayout(new FlowLayout());
dog.add(lbl);
dog.add(btn);
dog.setSize(300,100);
dog.show();
}
else
{//文件没有加密过,进行加密
final Dialog d1=new Dialog(keySecurity.this,"输入密码",false);
Label dl1=new Label("请输入密码:");
Label dl2=new Label("请再次输入密码:");
final TextField dtf1=new TextField(10);
dtf1.setEchoChar('*');//将文本域设置回显符号为“*”
final TextField dtf2=new TextField(10);
dtf2.setEchoChar('*');
Button db1=new Button("确定");
Button db2=new Button("取消");
d1.setLayout(new FlowLayout());
d1.add(dl1);
d1.add(dtf1);
d1.add(dl2);
d1.add(dtf2);
d1.add(db1);
d1.add(db2);
db1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
final Dialog d2=new Dialog(keySecurity.this,"加密情况",false);
Label d2l=new Label("");
Button d2b=new Button("确定");
d2b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d2.dispose();
d1.dispose();
}
}); 
s1=dtf1.getText();
s2=dtf2.getText();try
{
/******************将密码s1写入文件中
以便下次解密时调用之前输入的密码***/
writeFile(FileName+".txt",s1);
if(s1.equals("")||s2.equals(""))
{
d2l.setText("输入的密码为空");
}
else if(s1.equals(s2)) 
{
/****加密打开的文件***/
try
{
Cipher cipher1=Cipher.getInstance("DES");
KeyGenerator kg=KeyGenerator.getInstance("DES");
Key desKey=kg.generateKey();
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DES");
DESKeySpec keyspec=(DESKeySpec)keyfactory.getKeySpec(kg.generateKey(),DESKeySpec.class);
byte[] rawkey=keyspec.getKey();
//把原密钥写入文件
FileOutputStream out=new FileOutputStream("key"+FileName+".txt");
out.write(rawkey);
cipher1.init(Cipher.ENCRYPT_MODE,desKey);
FileInputStream fis=new FileInputStream(DirName+FileName);
CipherInputStream cis1=new CipherInputStream(fis,cipher1);
byte[] b1=new byte[1024];
int i1=cis1.read(b1);
FileOutputStream fos=new FileOutputStream(DirName+FileName);
while(i1!=-1)
{
fos.write(b1,0, i1);
i1=cis1.read(b1);
}
fis.close();
cis1.close();
fos.close();
out.close();
}
catch(Exception et)
{
System.err.println(et);
}
d2l.setText("加密成功,密码为"+s1);
}
else

d2l.setText("两次密码不匹配");
}
}
catch(Exception en)
{
System.err.print(en);
}
d2.setLayout(new FlowLayout());
d2.add(d2l);
d2.add(d2b);
d2.setSize(200,100);
d2.show();
}
});db2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d1.dispose();
}
});
d1.setSize(250,150);
d1.show();

}
});
add(b2);
Button b3=new Button("解密");
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
final Dialog d3=new Dialog(keySecurity.this,"输入密码",false);
Label d3l=new Label("请输入密码:");
final TextField d3tf1=new TextField(10);
d3tf1.setEchoChar('*');
Button d3b1=new Button("确定");
Button d3b2=new Button("取消");
d3.setLayout(new FlowLayout());
d3.add(d3l);
d3.add(d3tf1);
d3.add(d3b1);
d3.add(d3b2);
d3b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
final Dialog d4=new Dialog(keySecurity.this,"解密情况",false);
Label d4l=new Label("");
Button d4b=new Button("确定");
d4b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d4.dispose();
d3.dispose();
}
}); try
{
String s4=readFile(FileName+".txt");
s4=s4.trim();
String s3=d3tf1.getText();
if(s3.equals(s4)) 
{
/****让用户输入密码,密码正确的话,开始解密,
然后弹出个对话框,解密成功,还应该立刻将
原存储密码的txt文件同时删除。********/
try
{
Cipher cipher2=Cipher.getInstance("DES");
DataInputStream in=new DataInputStream(new FileInputStream("key"+FileName+".txt"));
File f=new File("key"+FileName+".txt");
byte[] rawkey=new byte[(int)f.length()];
in.readFully(rawkey);
in.close();
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DES");
DESKeySpec keyspec=new DESKeySpec(rawkey);
SecretKey desKey=keyfactory.generateSecret(keyspec);
cipher2.init(Cipher.DECRYPT_MODE,desKey);
FileInputStream cis1=new FileInputStream(DirName+FileName);
CipherInputStream cis2=new CipherInputStream(cis1,cipher2);
FileOutputStream fos=new FileOutputStream(DirName+FileName);
byte[] b2=new byte[1024];
int i2=cis2.read(b2);
while(i2!=-1)
{
fos.write(b2,0,i2);
i2=cis2.read(b2);
}
d4l.setText("解密成功");
File ukey=new File(FileName+".txt");
File pkey=new File("key"+FileName+".txt");
ukey.delete();
pkey.delete();
}
catch(Exception et)
{
System.err.println(et);
}}
else
{
d4l.setText("两次密码不匹配或密码为空");
}
}
catch(Exception er)
{
System.err.println(er.toString());
}d4.setLayout(new FlowLayout());
d4.add(d4l);
d4.add(d4b);
d4.setSize(200,100);
d4.show();
}
});d3b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d3.dispose();
}
});
d3.setSize(200,100);
d3.show(); 
}
});
add(b3);
}
//将字符串写入指定文件中
public void writeFile(String f,String s)throws Exception 
{
FileOutputStream out=new FileOutputStream(f);
PrintStream p=new PrintStream(out);
p.println(s);
p.close(); 
}//将文件内容读出并存储在字符串中
public String readFile(String f)throws Exception
{
File keyfile=new File(f);
byte[] rawkey=new byte[(int)keyfile.length()];
FileInputStream fstream=new FileInputStream(f);
DataInputStream in=new DataInputStream(fstream);
in.readFully(rawkey);
in.close();
String s=new String(rawkey);
return s;
}public static void main(String[] args)
{
keySecurity keys=new keySecurity();
keys.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
keys.pack();
keys.show();
}
}

解决方案 »

  1.   

    package ejc.test;import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.io.FileInputStream;
    import java.io.OutputStream;
    import javax.crypto.*;
    import javax.crypto.Cipher;
    import javax.crypto.spec.*;
    import java.security.*;
    import java.security.spec.*;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Vector;public class keySecurity extends Frame
    {
    static String DirName;
    static String FileName;
    static String key_map;
    static String s2;
    static String path;
    static File key_root;
    static File codef;
    static ObjectInputStream objin;
    static ObjectOutputStream objout;
    static FileInputStream instr;
    static FileOutputStream outstr;
    final String mycode="/mycode.txt";
    static KeyContainer keyc;
    class KeyContainer implements java.io.Serializable{
    private Map khash;
    private Vector fvector;
    }
    public keySecurity()
    {File files[]=File.listRoots();
    key_root=new File(files[0].getAbsolutePath()+"DESS");
    key_root.mkdir();
    codef=new File(key_root+mycode);
    try{
    if(codef.exists())
    {
    System.out.println("Come into 50");
    instr=new FileInputStream(codef);
    objin=new ObjectInputStream(instr);
    keyc=(KeyContainer)objin.readObject();
    }else{
    keyc=new KeyContainer();
    keyc.khash=new HashMap();
    keyc.fvector=new Vector(0,1);
    codef.createNewFile();
    }
    }catch(Exception e){
    //忽略;
    }setTitle("02级计算机1班 姓名:查继华 学号:02081001 课程设计");
    this.setLayout(new FlowLayout());
    this.setSize(400,800);
    Label l1=new Label("请选择要操作的文件:");
    add(l1);
    final TextField tf1=new TextField(50);
    add(tf1);
    Button b1=new Button("打开");
    b1.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    //点击打开按钮,应该出现一个对话框,对话框的功能是让用户选择
    //要打开的文件
    FileDialog fd=new FileDialog(keySecurity.this,"选择要操作的文件",FileDialog.LOAD);
    fd.show();
    DirName=fd.getDirectory();//获取用户选定的文件名路径
    FileName=fd.getFile();//获取用户选定的文件名
    path=DirName+FileName;
    tf1.setText(path);
    }
    });
    add(b1);
    Button b2=new Button("加密");
    b2.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    //弹出一个对话框,让用户输入密码,再次确认密码,还有确定,
    //取消按钮,点确定后,开始加密!!!若文件已经是加密过的
    //则弹出对话框,提示已经加密的文件!
    //再弹出个对话框,告诉用户加密成功,密码为***。
    if(path.trim().equals("")){
    return;
    }
    if(keyc.fvector.contains(path))
    {//文件已经加密过
    final Dialog dog=new Dialog(keySecurity.this,"提示窗口",false);
    Label lbl=new Label("你要加密的文件已经加密过了,点确定退出程序");
    Button btn=new Button("确定");
    btn.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    dog.setVisible(false);
    }
    });
    dog.setLayout(new FlowLayout());
    dog.add(lbl);
    dog.add(btn);
    dog.setSize(300,100);
    dog.show();
    }
    else
    {//文件没有加密过,进行加密
    final Dialog d1=new Dialog(keySecurity.this,"输入密码",false);
    Label dl1=new Label("请输入密码:");
    Label dl2=new Label("请再次输入密码:");
    final TextField dtf1=new TextField(10);
    dtf1.setEchoChar('*');//将文本域设置回显符号为“*”
    final TextField dtf2=new TextField(10);
    dtf2.setEchoChar('*');
    Button db1=new Button("确定");
    Button db2=new Button("取消");
    d1.setLayout(new FlowLayout());
    d1.add(dl1);
    d1.add(dtf1);
    d1.add(dl2);
    d1.add(dtf2);
    d1.add(db1);
    d1.add(db2);
    db1.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    final Dialog d2=new Dialog(keySecurity.this,"加密情况",false);
    Label d2l=new Label("");
    Button d2b=new Button("确定");
    d2b.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    d2.dispose();
    d1.dispose();
    }
    }); 
    key_map=dtf1.getText();
    s2=dtf2.getText();try
    {
    /******************将密码s1写入文件中
    以便下次解密时调用之前输入的密码***/if(key_map.equals("")||s2.equals(""))
    {
    d2l.setText("输入的密码为空");
    }
    else if(key_map.equals(s2)) 
    {
    /****加密打开的文件***/
    try
    {
    KeyGenerator keygen=KeyGenerator.getInstance("DES");
    keygen.init(56);
    Key key=keygen.generateKey();
    Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE,key);
    File srcfile=new File(DirName+FileName);
    FileInputStream fin=new FileInputStream(srcfile);
    byte[] buff=new byte[(int)srcfile.length()];
    fin.read(buff);
    byte[] encode_buff=cipher.doFinal(buff);
    FileOutputStream fout=new FileOutputStream(DirName+FileName);
    fout.write(encode_buff); 
    fin.close();
    fout.close();
    keyc.khash.put(key_map.trim(),key);
    keyc.fvector.add(path);
    }
    catch(Exception et)
    {
    System.err.println(et);
    }
    d2l.setText("加密成功,密码为"+key_map);
    }
    else

    d2l.setText("两次密码不匹配");
    }
    }
    catch(Exception en)
    {
    System.err.print(en);
    }
    d2.setLayout(new FlowLayout());
    d2.add(d2l);
    d2.add(d2b);
    d2.setSize(200,100);
    d2.show();
    }
    });db2.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    d1.dispose();
    }
    });
    d1.setSize(250,150);
    d1.show();

    }
    });
    add(b2);
    Button b3=new Button("解密");
    b3.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    final Dialog log=new Dialog(keySecurity.this,"输入密码",false);
    final Label info=new Label("请输入密码:");
    final TextField tf=new TextField(10);
    tf.setEchoChar('*');
    Button d3b1=new Button("确定");
    Button d3b2=new Button("取消");
    log.setLayout(new FlowLayout());
    log.add(info);
    log.add(tf);
    log.add(d3b1);
    log.add(d3b2);
    d3b1.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    final Dialog log2=new Dialog(keySecurity.this,"解密情况",false);
    Label label=new Label("");
    Button d4b=new Button("确定");
    d4b.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    try
    {/****让用户输入密码,密码正确的话,开始解密,
    然后弹出个对话框,解密成功,还应该立刻将
    原存储密码的txt文件同时删除。********/
    String key_map=tf.getText();
    try
    {
    path=DirName+FileName;
    if(path.trim().equals("")){
    return;
    }
    if(keyc.fvector.contains(path))
    {
    System.out.println("Cone into 270");
    keyc.fvector.remove(path);
    Key rekey=(Key)keyc.khash.get(key_map);
    if(rekey!=null)
    {
    keyc.khash.remove(key_map);
    Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE,rekey);
    File uncode=new File(path);
    instr=new FileInputStream(uncode);
    byte buff[]=new byte[(int)uncode.length()];
    instr.read(buff);
    buff=cipher.doFinal(buff);
    outstr=new FileOutputStream(uncode);
    outstr.write(buff);
    instr.close();
    outstr.close();
    log2.setVisible(false);
    info.setText("解密成功!");
    }else{
    log2.setVisible(false);
    info.setText("解密失败,密钥丢失!");
    }
    }else{
    log2.setVisible(false); 
    info.setText("文件还没有加密!");
    }
    }
    catch(Exception et)
    {
    System.err.println(et);
    }
    }
    catch(Exception er)
    {
    System.err.println(er.toString());
    }
    }
    }); 
    log2.setLayout(new FlowLayout());
    log2.add(label);
    log2.add(d4b);
    log2.setSize(200,100);
    log2.show();
    }
    });d3b2.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    log.dispose();
    }
    });
    log.setSize(200,100);
    log.show(); 
    }
    });
    add(b3);
    }
    public static void main(String[] args)
    {
    keySecurity keys=new keySecurity();
    keys.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e)
    {
    try{
    codef.delete();
    outstr=new FileOutputStream(codef);
    objout=new ObjectOutputStream(outstr);
    objout.writeObject(keyc);
    }catch(Exception ex){
    System.exit(-1);
    }
    System.exit(0);
    }
    });
    keys.pack();
    keys.show();
    }
    }