⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileencrypter.java.bak

📁 使用三重DES加密算法和替代加密算法对文件进行加密的小程序
💻 BAK
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

//================================================================================================================================
//构造窗体,注册事件监听,事件响应
public class FileEncrypter extends JFrame
{
	public static final int WIDTH = 550;
	public static final int HEIGHT = 200;
	public static AbstractButton button;
	FileEncrypter()
	{
		setSize(WIDTH,HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		Toolkit tk = Toolkit.getDefaultToolkit();
		final Dimension screenSize = tk.getScreenSize();
		setLocation((screenSize.width - WIDTH)/2, (screenSize.height - HEIGHT)/2); 
		setTitle("文件加密器");
		final Container c = this.getContentPane();
		c.setLayout( new FlowLayout());
		JMenuBar bar = new JMenuBar();
		JMenu setting,help;
		setting = new JMenu ("设置(S)");
		help = new JMenu ("帮助(H)");
		JMenuItem about;
		about = new JMenuItem("关于...",KeyEvent.VK_A);
		about.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				JDialog d = new JDialog();
				d.setTitle("关于FileEncrypter");
				d.setLocation((screenSize.width - WIDTH + 200)/2, (screenSize.height - HEIGHT)/2);
				d.setSize(350,200);
				JPanel p=new JPanel();
				p.setLayout(new GridLayout(5,1));
				d.add(p);
				JLabel userName=new JLabel("           本机的用户名为:"+System.getProperty("user.name"));
				JLabel osName=new JLabel("           本机的操作系统是:"+System.getProperty("os.name"));
				JLabel javaVersion=new JLabel("           本机中所安装的Java SDK的版本号是:"+System.getProperty("java.version"));
				p.add(new JLabel("            FileEncrypter程序 "));
				p.add(osName);
				p.add(userName);
				p.add(javaVersion);
				p.add(new JLabel("            200610404141 马宗骁"));
				getDefaultCloseOperation();
				d.setResizable(false);
				d.setVisible(true);
			}
		});
		JRadioButtonMenuItem specialRadio1 = new JRadioButtonMenuItem("替代加密算法");
		JRadioButtonMenuItem specialRadio2 = new JRadioButtonMenuItem("三重DES加密算法");
		class ItemHandler implements ItemListener
		{
			public void itemStateChanged(ItemEvent e)
			{
				button = (AbstractButton) e.getItem();
			}
		}
		specialRadio1.addItemListener(new ItemHandler());
		specialRadio2.addItemListener(new ItemHandler());
		ButtonGroup buttonGroup1 = new ButtonGroup();
		bar.add(setting);
		setting.setMnemonic(KeyEvent.VK_F);
		bar.add(help);
		help.setMnemonic(KeyEvent.VK_H);
		setting.add(specialRadio1);
		setting.add(specialRadio2);
		buttonGroup1.add(specialRadio1);
		buttonGroup1.add(specialRadio2);
		help.add(about);
		setJMenuBar (bar);		
		final FilePanel fp = new FilePanel("文件选择");
		c.add(fp);
		final KeyPanel pp = new KeyPanel("    密码     ");
		c.add(pp);
		JButton jbE = new JButton("加密");
		c.add(jbE);
		jbE.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				if(button == null)
				JOptionPane.showMessageDialog(null,"请选择加密方式!","提示",JOptionPane.OK_OPTION);
				else
				{ 
				  File file = new File(fp.getFileName());
				  if (file.exists()&&button.getText().equals("三重DES加密算法"))
				  encrypt_des(file.getAbsoluteFile(),pp.getKey());
				  else if(file.exists()&&button.getText().equals("替代加密算法"))
				  encrypt_tidai(file.getAbsoluteFile(),pp.getKey());
				  else
				  JOptionPane.showMessageDialog(null,"请选择文件!","提示",JOptionPane.OK_OPTION);
				}
			}
		});
		JButton jbD = new JButton("解密");
		c.add(jbD);
		jbD.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				if(button == null)
				JOptionPane.showMessageDialog(null,"请选择加密方式!","提示",JOptionPane.OK_OPTION);
				else
				{
				  File file = new File(fp.getFileName());
			    if (file.exists()&&button.getText().equals("三重DES加密算法"))
			  	decrypt_des(file.getAbsoluteFile(),pp.getKey());
			  	else if(file.exists()&&button.getText().equals("替代加密算法"))
			  	decrypt_kaisa(file.getAbsoluteFile(),pp.getKey());
			    else
			    JOptionPane.showMessageDialog(null,"请选择文件!","提示",JOptionPane.OK_OPTION);
			  }			  
			}
		});
		setVisible(true);
	}
//================================================================================================================================
//3DES算法	
  private void encrypt_des(File fileIn,String sKey)
	{
	  /*
	  在此添加加密函数
	  实现加密
	  */
	  try
	  { 
      if(sKey.length() == 48)
      { 
        byte[] bytK1 = getKeyByStr(sKey.substring(0,16)); 
        byte[] bytK2 = getKeyByStr(sKey.substring(16,32)); 
        byte[] bytK3 = getKeyByStr(sKey.substring(32,48)); 

        FileInputStream fis = new FileInputStream(fileIn); 
        byte[] bytIn = new byte[(int)fileIn.length()]; 
        for(int i = 0;i<fileIn.length();i++)
        { 
          bytIn[i] = (byte)fis.read(); 
        } 
        //加密 
        byte[] bytOut = encryptByDES(encryptByDES( 
        encryptByDES(bytIn,bytK1),bytK2),bytK3); 
        String fileOut = fileIn.getPath() + ".tdes"; 
        FileOutputStream fos = new FileOutputStream(fileOut); 
        for(int i = 0;i<bytOut.length;i++)
        { 
          fos.write((int)bytOut[i]); 
        } 
        fos.close(); 
        JOptionPane.showMessageDialog(this,"加密成功!","提示",JOptionPane.OK_OPTION); 
      }
      else 
      JOptionPane.showMessageDialog(this,"密码长度必须等于48!","错误信息",JOptionPane.ERROR_MESSAGE); 
    }
    catch(Exception e)
    { 
      e.printStackTrace(); 
    } 

	}
/*
在此添加解密函数
实现解密
*/
/** 
解密函数 
输入: 
要解密的文件,密码(由0-F组成,共48个字符,表示3个8位的密码)如: 
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746 
其中: 
AD67EA2F3BE6E5AD DES密码一 
D368DFE03120B5DF DES密码二 
92A8FD8FEC2F0746 DES密码三 
输出: 
对输入的文件解密后,保存到用户指定的文件中。 
*/ 
  private void decrypt_des(File fileIn,String sKey)
  { 
    try
    { 
      if(sKey.length() == 48)
      { 
        String strPath = fileIn.getPath(); 
        if(strPath.substring(strPath.length()-5).toLowerCase().equals(".tdes")) 
        strPath = strPath.substring(0,strPath.length()-5); 
        else
        { 
          JOptionPane.showMessageDialog(this,"不是合法的加密文件!","提示",JOptionPane.OK_OPTION); 
          return; 
        } 
        JFileChooser chooser = new JFileChooser(); 
        chooser.setCurrentDirectory(new File(".")); 
        chooser.setSelectedFile(new File(strPath)); 
        //用户指定要保存的文件 
        int ret = chooser.showSaveDialog(this); 
        if(ret==JFileChooser.APPROVE_OPTION)
        { 
          byte[] bytK1 = getKeyByStr(sKey.substring(0,16)); 
          byte[] bytK2 = getKeyByStr(sKey.substring(16,32)); 
          byte[] bytK3 = getKeyByStr(sKey.substring(32,48)); 

          FileInputStream fis = new FileInputStream(fileIn); 
          byte[] bytIn = new byte[(int)fileIn.length()]; 
          for(int i = 0;i<fileIn.length();i++)
          { 
            bytIn[i] = (byte)fis.read(); 
          } 
          //解密 
          byte[] bytOut = decryptByDES(decryptByDES( 
          decryptByDES(bytIn,bytK3),bytK2),bytK1); 
          File fileOut = chooser.getSelectedFile(); 
          fileOut.createNewFile(); 
          FileOutputStream fos = new FileOutputStream(fileOut); 
          for(int i = 0;i<bytOut.length;i++)
          { 
            fos.write((int)bytOut[i]); 
          } 
          fos.close(); 
          JOptionPane.showMessageDialog(this,"解密成功!","提示",JOptionPane.OK_OPTION); 
        } 
      }
      else 
      JOptionPane.showMessageDialog(this,"密码长度必须等于48!","错误信息",JOptionPane.ERROR_MESSAGE); 
    }
    catch(Exception e)
    { 
      JOptionPane.showMessageDialog(this,"解密失败,请核对密码!","提示",JOptionPane.OK_OPTION); 
    } 
  } 

/** 
用DES方法加密输入的字节 
bytKey需为8字节长,是加密的密码 
*/ 
  private byte[] encryptByDES(byte[] bytP,byte[] bytKey) throws Exception
  { 
    DESKeySpec desKS = new DESKeySpec(bytKey); 
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); 
    SecretKey sk = skf.generateSecret(desKS); 
    Cipher cip = Cipher.getInstance("DES"); 
    cip.init(Cipher.ENCRYPT_MODE,sk); 
    return cip.doFinal(bytP); 
  } 

/** 
用DES方法解密输入的字节 
bytKey需为8字节长,是解密的密码 
*/ 
  private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception
  { 
    DESKeySpec desKS = new DESKeySpec(bytKey); 
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); 
    SecretKey sk = skf.generateSecret(desKS); 
    Cipher cip = Cipher.getInstance("DES"); 
    cip.init(Cipher.DECRYPT_MODE,sk); 
    return cip.doFinal(bytE); 
  } 

/** 
输入密码的字符形式,返回字节数组形式。 
如输入字符串:AD67EA2F3BE6E5AD 
返回字节数组:{173,103,234,47,59,230,229,173} 
*/ 
  private byte[] getKeyByStr(String str)
  { 
    byte[] bRet = new byte[str.length()/2]; 
    for(int i=0;i<str.length()/2;i++)
    { 
      Integer itg = new Integer(16*getChrInt(str.charAt(2*i)) + getChrInt(str.charAt(2*i+1))); 
      bRet[i] = itg.byteValue(); 
    } 
    return bRet; 
  } 
/** 
计算一个16进制字符的10进制值 
输入:0-F 
*/ 
  private int getChrInt(char chr)
  { 
    int iRet=0; 
    if(chr=="0".charAt(0)) iRet = 0; 
    if(chr=="1".charAt(0)) iRet = 1; 
    if(chr=="2".charAt(0)) iRet = 2; 
    if(chr=="3".charAt(0)) iRet = 3; 
    if(chr=="4".charAt(0)) iRet = 4; 
    if(chr=="5".charAt(0)) iRet = 5; 
    if(chr=="6".charAt(0)) iRet = 6;
    if(chr=="7".charAt(0)) iRet = 7; 
    if(chr=="8".charAt(0)) iRet = 8; 
    if(chr=="9".charAt(0)) iRet = 9; 
    if(chr=="A".charAt(0)) iRet = 10;
    if(chr=="B".charAt(0)) iRet = 11; 
    if(chr=="C".charAt(0)) iRet = 12; 
    if(chr=="D".charAt(0)) iRet = 13; 
    if(chr=="E".charAt(0)) iRet = 14; 
    if(chr=="F".charAt(0)) iRet = 15; 
    return iRet; 
  }
//================================================================================================================================
//替代加密算法  
	private void encrypt_tidai(File fileIn,String sKey)
	{
		try
		{
			if(sKey.length() <= 2)
			{
			  int n = Integer.parseInt(sKey);
			  FileInputStream fis = new FileInputStream(fileIn);
			  byte[] bytIn = new byte[(int)fileIn.length()];
			  byte[] bytOut = new byte[(int)fileIn.length()];
			  for(int i = 0;i<fileIn.length();i++)
			  {
				  bytIn[i] = (byte)fis.read();
			  }
			  //jiami
			  for(int i = 0;i<fileIn.length();i++)
			  bytOut[i] = (byte)(bytIn[i]+n);
			  String fileOut = fileIn.getPath();// + ".tidai";
			  FileOutputStream fos = new FileOutputStream(fileOut);
			  for(int i = 0;i<bytOut.length;i++)
			  {
				  fos.write((int)bytOut[i]);
			  }
			  fos.close();
			  JOptionPane.showMessageDialog(this,"替代加密成功!","提示",JOptionPane.OK_OPTION);
		  }
		  else
		  JOptionPane.showMessageDialog(this,"密码长度不正确!","错误信息",JOptionPane.ERROR_MESSAGE);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	private void decrypt_kaisa(File fileIn,String sKey)
	{
		try
		{
			if(sKey.length() <= 2)
			{
				String strPath = fileIn.getPath();
				if(strPath.substring(strPath.length()-6).toLowerCase().equals(".tidai"))
				strPath = strPath.substring(0,strPath.length()-6);
				else
				{
					JOptionPane.showMessageDialog(this,"不是合法的加密文件!","提示",JOptionPane.OK_OPTION);
					return;
				}
				JFileChooser chooser = new JFileChooser();
				chooser.setCurrentDirectory(new File(""));
				chooser.setSelectedFile(new File(strPath));
				//用户指定要保存的文件 
				int ret = chooser.showSaveDialog(this);
				if(ret==JFileChooser.APPROVE_OPTION)
				{
					int n = Integer.parseInt(sKey);
					FileInputStream fis = new FileInputStream(fileIn);
					byte[] bytIn = new byte[(int)fileIn.length()];
					byte[] bytOut = new byte[(int)fileIn.length()];
					for(int i = 0;i<fileIn.length();i++)
					{
						bytIn[i] = (byte)fis.read();
					}
					//解密
					for(int i = 0;i<fileIn.length();i++)
					bytOut[i] = (byte)(bytIn[i]-n);
					File fileOut = chooser.getSelectedFile();
					fileOut.createNewFile();
					FileOutputStream fos = new FileOutputStream(fileOut);
					for(int i = 0;i<bytOut.length;i++)
					{
						fos.write((int)bytOut[i]);
					}
					fos.close();
					JOptionPane.showMessageDialog(this,"解密成功!","提示",JOptionPane.OK_OPTION);
				}
			}
			else
			JOptionPane.showMessageDialog(this,"密码长度必须小于等于2!","错误信息",JOptionPane.ERROR_MESSAGE);
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(this,"解密失败,请核对密码!","提示",JOptionPane.OK_OPTION);
		}
	}
  private byte[] decryptByKS(byte[] bytE,byte[] bytKey)
  {
  	return bytE;
  }
//================================================================================================================================
//主函数
	public static void main(String args[])
	{
		FileEncrypter fe = new FileEncrypter();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -