使用AES算法对文件进行加密解密(JAVA+Eclipse)

一、项目中引用第三方类库的方法
    Bouncy Castle类库的用法(如何在自己的项目中使用第三方类库)

    1)手动配置

  •     将.jar,src,javadoc拷到项目目录下
  •    项目名,右键选build path-configure build path

    2)使用Maven 或Gradle来配置//在线配置第三方依赖包

  •     http://mvnrepository.com 搜索 bouncy castle
  •     新建Gradle Project(File->New->other->Gradle->Gradle Project)
  •     找到 bouncy castle最新版本的gradle配置字符串将其添加到项目build.gradle配置文件中的dependencies条目的最后(}前的位置处)。添加完后,保存build.gradle配置文件,然后在项目身上右键->gradle->refresh gradle project.
二、最终事先效果(没有设置选择解密后文件保存位置的功能,只能存在于加密文件相同的位置)

使用AES算法对文件进行加密解密(JAVA+Eclipse)_第1张图片

三、文件加密解密程序实现主要代码(秘钥自动生成,不需要用户输入秘钥)
public class MyFileEncryptor {
	@SuppressWarnings("static-access")
	//文件加密的实现方法
	public static void encryptFile(String fileName,String encryptedFileName){
		try {
			FileInputStream fis = new FileInputStream(fileName);
			FileOutputStream fos = new FileOutputStream(encryptedFileName);
			
			//秘钥自动生成
			KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");
			keyGenerator.init(128);
			Key key=keyGenerator.generateKey();
			
			
			byte[] keyValue=key.getEncoded();
			
			fos.write(keyValue);//记录输入的加密密码的消息摘要
			
			SecretKeySpec encryKey= new SecretKeySpec(keyValue,"AES");//加密秘钥
			
			byte[] ivValue=new byte[16];
			Random random = new Random(System.currentTimeMillis());
			random.nextBytes(ivValue);
			IvParameterSpec iv = new IvParameterSpec(ivValue);//获取系统时间作为IV
			
			fos.write("MyFileEncryptor".getBytes());//文件标识符

			fos.write(ivValue);	//记录IV
			Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
			cipher.init(cipher.ENCRYPT_MODE, encryKey,iv);
			
			CipherInputStream cis=new CipherInputStream(fis, cipher);
			
			byte[] buffer=new byte[1024];
			int n=0;
			while((n=cis.read(buffer))!=-1){
				fos.write(buffer,0,n);		
			}
			cis.close();
			fos.close();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	@SuppressWarnings("static-access")
	//文件解密的实现代码
	public static void decryptedFile(String encryptedFileName,String decryptedFileName){
		
			try {
				FileInputStream fis = new FileInputStream(encryptedFileName);
				FileOutputStream fos = new FileOutputStream(decryptedFileName);	
				
				byte[] fileIdentifier=new byte[15];
				
				byte[] keyValue=new byte[16];
				fis.read(keyValue);//读记录的文件加密密码的消息摘要
				fis.read(fileIdentifier);				
				if(new String (fileIdentifier).equals("MyFileEncryptor")){
					SecretKeySpec key= new SecretKeySpec(keyValue,"AES");					
					byte[] ivValue= new byte[16];
					fis.read(ivValue);//获取IV值
					IvParameterSpec iv= new IvParameterSpec(ivValue);
					Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
					cipher.init(cipher.DECRYPT_MODE, key,iv);
					CipherInputStream cis= new CipherInputStream(fis, cipher);												
					byte[] buffer=new byte[1024];
					int n=0;
					while((n=cis.read(buffer))!=-1){
						fos.write(buffer,0,n);		
					}
					cis.close();
					fos.close();
					JOptionPane.showMessageDialog(null, "解密成功");	
				}else{
					JOptionPane.showMessageDialog(null, "文件不是我加密的,爱找谁着谁去");
				}
			} catch (InvalidKeyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (HeadlessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidAlgorithmParameterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
	}
	public static void main(String[] args) {
		Security.addProvider(new BouncyCastleProvider());
	}
}
图形界面的实现代码:
public class Encryptor extends JFrame {

	private JPanel contentPane;
	private JTextField textFieldSelected;
	private JButton btnEncryptFile;
	private JButton btnDecryptFile;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		Security.addProvider(new BouncyCastleProvider());
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Encryptor frame = new Encryptor();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Encryptor() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		btnEncryptFile = new JButton("\u52A0\u5BC6");
		btnEncryptFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String fileName=textFieldSelected.getText();
				String encryptedFileName=fileName+".enc";	
				MyFileEncryptor.encryptFile(fileName, encryptedFileName);								
				JOptionPane.showMessageDialog(null, "加密成功");	
			}
		});
		btnEncryptFile.setBounds(14, 213, 113, 27);
		contentPane.add(btnEncryptFile);
		
		btnDecryptFile = new JButton("\u89E3\u5BC6");
		btnDecryptFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String decryptedFile=textFieldSelected.getText();
				String fileType=".enc";
				String decryptedFileName=decryptedFile.substring(0, decryptedFile.length()-fileType.length());			
				String encryptedFileName=textFieldSelected.getText();
				MyFileEncryptor.decryptedFile(encryptedFileName, decryptedFileName);
			}
		});
		btnDecryptFile.setBounds(292, 213, 113, 27);
		contentPane.add(btnDecryptFile);
		
		textFieldSelected = new JTextField();
		textFieldSelected.setBounds(14, 92, 360, 24);
		contentPane.add(textFieldSelected);
		textFieldSelected.setColumns(10);
		
		JButton buttonSelect = new JButton("......");
		buttonSelect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser=new JFileChooser("D:");
				if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
					textFieldSelected.setText(fileChooser.getSelectedFile().getPath());
				}
			}
		});
		buttonSelect.setBounds(378, 91, 40, 27);
		contentPane.add(buttonSelect);
		
		JLabel label = new JLabel("\u9009\u62E9\u6587\u4EF6\uFF1A");
		label.setBounds(14, 74, 97, 18);
		contentPane.add(label);
		
		JLabel lblAes = new JLabel("AES\u52A0\u5BC6\uFF0C\u5BC6\u94A5\u957F\u5EA6128");
		lblAes.setBounds(132, 29, 153, 18);
		contentPane.add(lblAes);
	}
}


你可能感兴趣的:(JAVA,密码学)